I'd like to check if two arrays are equal. I mean: same size, same index, same values. How can I do that?
Using !==
as suggested by a user, I expect that the following would print enter if at least one element in the array(s) are different, but in fact it does not.
if (($_POST['atlOriginal'] !== $oldAtlPosition)
or ($_POST['atl'] !== $aext)
or ($_POST['sidesOriginal'] !== $oldSidePosition)
or ($_POST['sidesOriginal'] !== $sideext)) {
echo "enter";
}
Use php function array_diff(array1, array2); It will return a the difference between arrays. If its empty then they're equal.
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
See Array Operators.
EDIT
The inequality operator is !=
while the non-identity operator is !==
to match the equality
operator ==
and the identity operator ===
.
According to this page.
NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).
Testing two indexed arrays, which elements are in different order, using $a == $b
or $a === $b
fails, for example:
<?php
(array("x","y") == array("y","x")) === false;
?>
That is because the above means:
array(0 => "x", 1 => "y")
vs. array(0 => "y", 1 => "x")
.
To solve that issue, use:
<?php
function array_equal($a, $b) {
return (
is_array($a)
&& is_array($b)
&& count($a) == count($b)
&& array_diff($a, $b) === array_diff($b, $a)
);
}
?>
Comparing array sizes was added (suggested by super_ton) as it may improve speed.
Try serialize. This will check nested subarrays as well.
$foo =serialize($array_foo);
$bar =serialize($array_bar);
if ($foo == $bar) echo "Foo and bar are equal";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With