How to compare two arrays
Short answer
The == operator compares key–value pairs; === also compares order and types:
<?php
var_dump(['a' => 1, 'b' => 2] == ['b' => 2, 'a' => 1]);
var_dump(['a' => 1, 'b' => 2] === ['b' => 2, 'a' => 1]);Output:
bool(true)
bool(false)What was added and what is gone
array_diff() returns the values of the first array missing from the second:
<?php
$before = ['php', 'sql', 'css'];
$after = ['php', 'css', 'js'];
echo implode(', ', array_diff($after, $before)), ' | ', implode(', ', array_diff($before, $after));Output:
js | sqlCommon elements
array_intersect() does that:
<?php
echo implode(', ', array_intersect(['php', 'sql', 'css'], ['php', 'css', 'js']));Output:
php, cssFunctions used in this recipe
- array_diff — Returns the values of the first array that are absent from the others.
- array_intersect — Returns the values present in every array.
- array_diff_assoc — Returns the elements of the first array missing from the others, comparing both keys and values.