如何检查两个数组是否有相同的元素,而不管它们的索引位置



你能让我知道我如何检查两个数组是否具有相同的元素,并返回true或false,无论它们的元素索引位置如何?你可以看到$a==$b没有这样做

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");
if($a==$b){
   echo "yes";
}else{
 echo "no";
}

Use Array Diff:

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");

$result = array_diff($a, $b);
if(count($result) > 0){
   echo "yes";
}else{
   echo "no";
}

只需将您的数组对象包含在sort()函数中,同时比较它们

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");
if(sort($a) == sort($b)){
    echo "yes";
}else{
    echo "no";
}

您可以sort()两个数组,然后检查是否相等。这样的:

<?php
$a=array("apple","banana", "strawberry");
$b=array("strawberry", "apple","banana");
$a = sort($a);
$b = sort($b);
if($a==$b){
   echo "yes";
}else{
 echo "no";
}
?>

可以使用array_diff()函数

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");
$diff = array_diff($a, $b);
if(count($diff) > 0){
   echo "yes";
}
else{
   echo "no";
}
print_r($diff);

如果$diff返回一个空数组,则表示$a$b之间没有区别。

否则,$diff返回不同的元素。

查看手册,array_diff

相关内容

  • 没有找到相关文章