Skip to content
PHP Logo

How does PHP handle comparisons between arrays with different key-value pairs?

When comparing arrays with different key-value pairs in PHP, the comparison will return false because the arrays are not considered equal. To solve this issue, you can use the array_diff() function to compare the values of the arrays without considering the keys.

php
$array1 = ['key1' => 'value1', 'key2' => 'value2'];
$array2 = ['key1' => 'value1', 'key3' => 'value3'];

if (empty(array_diff($array1, $array2)) && empty(array_diff($array2, $array1))) {
    echo 'Arrays are equal';
} else {
    echo 'Arrays are not equal';
}