I'm looking for a way to check if two arrays are identical, for example
$a = array(
'1' => 12,
'3' => 14,
'6' => 11
);
$b = array(
'1' => 12,
'3' => 14,
'6' => 11
);
These two would be identical, but if a single value was changed, it would return false, I know I could write a function, but is there one already built?
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.
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 in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
You can just use $a == $b
if order doesn't matter, or $a === $b
if order does matter.
For example:
$a = array(
'1' => 12,
'3' => 14,
'6' => 11
);
$b = array(
'1' => 12,
'3' => 14,
'6' => 11
);
$c = array(
'3' => 14,
'1' => 12,
'6' => 11
);
$d = array(
'1' => 11,
'3' => 14,
'6' => 11
);
$a == $b; // evaluates to true
$a === $b; // evaluates to true
$a == $c; // evaluates to true
$a === $c; // evaluates to false
$a == $d; // evaluates to false
$a === $d; // evaluates to false
You can use
$a === $b // or $a == $b
example of usage:
<?php
$a = array(
'1' => 12,
'3' => 14,
'6' => 11
);
$b = array(
'1' => 12,
'3' => 14,
'6' => 11
);
echo ($a === $b) ? 'they\'re same' : 'they\'re different';
echo "\n";
$b['1'] = 11;
echo ($a === $b) ? 'they\'re same' : 'they\'re different';
which will return
they're same
they're different
demo
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