can you please let me know how I can check if two arrays have same elements and return true or false regardless of their elements index position? as you can see the $a==$b
is not doing this
$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";
}
You can sort()
both the arrays and then check for equality. Like this:
<?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";
}
?>
You can use array_diff() function.
$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);
If $diff returns an empty array, it means there are no differences between $a and $b.
Otherwise, $diff returns the elements which are differents.
Check the manual, array_diff.
Just enclose your array objects in sort()
function while comparing them.
$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");
if(sort($a) == sort($b)){
echo "yes";
}else{
echo "no";
}