首页 > 解决方案 > 如何检查包含与其他数组相同值的php数组

问题描述

我有两个数组,它们是$a$b,其中数组的值相同,但元素的索引不同。

$a 
Array ( [0] => there is bald spot on the inside or outside of tyre [1] => uneven tyre wear )
$b
Array ( [0] => uneven tyre wear [1] => there is bald spot on the inside or outside of tyre )

但是当我通过 using 进行比较时,即使数组中的元素相同$a == $b,它也会返回(只是元素的位置不同。)false

之前给出的解决方案是

$a = Array ( 
    0 => 'there is bald spot on the inside or outside of tyre',
    1 => 'uneven tyre wear'

);

$b = Array ( 
       0 => 'uneven tyre wear', 
       1 => 'there is bald spot on the inside or outside of tyre' 
    );

if(count(array_diff($a,$b)) == 0){
    echo "both array are identical";    

}

但是如果我从 $a 中删除一个元素

$a = Array ( 
    0 => 'there is bald spot on the inside or outside of tyre'
    //1 => 'uneven tyre wear'

);

如果使用上述解决方案,它仍然显示相同。

标签: phparrays

解决方案


使用array_diff()

if(count(array_diff($a,$b)) == 0){
    echo "both array are identical";    

}

输出:- https://3v4l.org/vEUiQ

注意:-如果两个数组大小不同(一个有更多元素,另一个有更少元素),那么您必须在使用时将更大的数组放在第一个位置array_diff()

检查此输出:- https://3v4l.org/9lNae


推荐阅读