Is there anyway to compare arrays in php using an inbuilt function, short of doing some sort of loop?
$a1 = array(1,2,3);
$a2 = array(1,2,3);
if (array_are_
Conclusion from the commentary here:
Comparison of array values being equal (after type juggling) and in the same order only:
array_values($a1) == array_values($a2)
Comparison of array values being equal (after type juggling) and in the same order and array keys being the same and in the same order:
array_values($a1) == array_values($a2) && array_keys($a1) == array_keys($a2)
array_intersect() returns an array containing all the common values.
get the array from user or input the array values.Use sort function to sort both arrays. check using ternary operator. If the both arrays are equal it will print arrays are equal else it will print arrays are not equal. there is no loop iteration here.
sort($a1);
sort($a2);
echo (($a1==$a2) ? "arrays are equal" : "arrays are not equal");
If you do not care about keys and that just the values then this is the best method to compare values and make sure the duplicates are counted.
$mag = '{"1":"1","2":"2","3":"3","4":"3"}';
$mag_evo = '1|2|3';
$test1 = array_values(json_decode($mag, true));
$test2 = array_values(explode('|', $mag_evo));
if($test1 == $test2) {
echo 'true';
}
This will not echo true as $mag has 2 values in the array that equal 3.
This works best if you only care about the values and keys and you do not care about duplication. $mag = '{"1":"1","2":"2","3":"3","4":"3"}'; $mag_evo = '1|2|3';
$test1 = json_decode($mag, true);
$test2 = explode('|', $mag_evo);
// There is no difference in either array.
if(!array_diff($test1, $test2) && !array_diff($test2, $test1)) {
echo 'true';
}
This will return true as all values are found in both arrays, but as noted before it does not care about duplication.
if ( $a == $b ) {
echo 'We are the same!'
}