I have two arrays and I want to compare the first with the second array. I have an IF statement and it currently does two checks:
names
first array (index 0-9) and compare it with the first name
of the second array (index 0). Keep doing the same thing until we've compared all the indices 0-9 on the first array with all indices 0-9 of the second array.I have tried using the in_array()
function and that works, but only with a single variable. Something like this in_array($firstArray[0], $secondArray)
works. Something like this:
if(mysqli_num_rows($result) > 0 && in_array($firstArray[0], $secondArray)){
exit("exiting now!");
}
else {
echo "continue to do stuff...";
}
However, when I put the whole array in the inArray, it won't work. Like this:
in_array($firstArray, $secondArray)
How can I achieve this?
You can use array_intersect if you want to know if they intersect, you can use array_diff to see if the two arrays have any differences.
if(mysqli_num_rows($result) > 0 && !array_diff($firstArray, $secondArray)){
exit("exiting now!");
} else {
echo "continue to do stuff...";
}
Example:
<?php
$array1 = array (1,2,3,4);
$array2 = array (3,2,1,5);
$array3 = array_diff($array1, $array2);
$array4 = array_intersect($array1, $array2);
echo "<pre>";
echo "Array 1
";
print_r($array1);
echo "Array 2
";
print_r($array2);
echo "Arrays Difference
";
print_r($array3);
echo "Arrays intersect
";
print_r($array4);
echo "</pre>";
?>
Output:
Array 1
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Array 2
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
)
Arrays Difference
Array
(
[3] => 4
)
Arrays intersect
Array
(
[0] => 1
[1] => 2
[2] => 3
)
I think you are looking for array_intersect() which returns the values that are common in two (or more) arrays. http://php.net/manual/en/function.array-intersect.php
It returns an array but if it returns an empty array then empty arrays are falsy.