I want to compare two arrays in PHP
Suppose I have two arrays:
$array1 = array(1, 3, 5);
$array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);
How to check that two arrays are equally the most efficient and correct and it doesn't need the * $ array2 keywords .
I want to create a function that should return true if the values ββare exactly the same, and false if any of them differ in both value (values) and number of elements.
Thanks for your time and reading.
source to share
In the simplest case, you can just use array_diff
. It ignores the keys in the second array as well as the order of the values. It will return an empty set if the arrays are equal:
if (count(array_diff($array1, $array2)) == 0) {
// equal
You can also compare arrays directly, after removing the keys from the second:
if ($array1 == array_values($array2)) {
This will additionally compare the order of the contained values.
source to share
Create a class containing an array and create this class for the Comparable interface like http://php.net/manual/language.oop5.interfaces.php#69467
source to share