PHP
Finding Differences Between Arrays by Values, Keys, or Both
Discover how to identify differences between PHP arrays using `array_diff`, `array_diff_assoc`, and `array_diff_key` for precise comparison by values or keys.
<?php
$array1 = ['apple', 'banana', 'orange', 'grape'];
$array2 = ['banana', 'grape', 'kiwi'];
// 1. Difference by values (ignores keys)
$diffValues = array_diff($array1, $array2);
echo "Difference by values:
";
print_r($diffValues);
echo "
---
";
$arrayA = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$arrayB = ['b' => 2, 'd' => 5, 'e' => 6];
// 2. Difference by values and keys
$diffAssoc = array_diff_assoc($arrayA, $arrayB);
echo "Difference by values and keys:
";
print_r($diffAssoc);
echo "
---
";
// 3. Difference by keys only
$diffKeys = array_diff_key($arrayA, $arrayB);
echo "Difference by keys only:
";
print_r($diffKeys);
How it works: This snippet showcases PHP's built-in functions for comparing arrays. `array_diff()` finds values present in the first array but not in any other array, ignoring keys. `array_diff_assoc()` compares both keys and values, returning entries from the first array that are not present with the same key-value pair in other arrays. `array_diff_key()` compares only the keys, returning entries from the first array whose keys are not found in any other array.