PHP

Finding Differences Between Two PHP Arrays

Learn to efficiently compare two PHP arrays and identify values present in one but not the other using `array_diff()`, `array_diff_assoc()`, and `array_diff_key()`.

<?php
$array1 = ['apple', 'banana', 'orange', 'grape'];
$array2 = ['banana', 'kiwi', 'apple', 'mango'];

// array_diff: Compares arrays and returns values in array1 that are not present in array2
$diffValues = array_diff($array1, $array2);
// Result: ['orange', 'grape']

$assoc1 = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow'];
$assoc2 = ['a' => 'red', 'e' => 'green', 'f' => 'blue'];
$assoc3 = ['g' => 'yellow', 'd' => 'purple'];

// array_diff_assoc: Compares arrays based on both keys and values
// Returns elements from $assoc1 whose key-value pair is not in $assoc2 or $assoc3
$diffAssoc = array_diff_assoc($assoc1, $assoc2, $assoc3);
// Result: ['b' => 'green', 'c' => 'blue', 'd' => 'yellow'] (because 'd'=>'yellow' is in $assoc1 but not in $assoc2, and 'd'=>'purple' in $assoc3 is different)

// array_diff_key: Compares arrays based on keys only
// Returns elements from $assoc1 whose key is not present in $assoc2 or $assoc3
$diffKeys = array_diff_key($assoc1, $assoc2, $assoc3);
// Result: ['b' => 'green', 'c' => 'blue'] (keys 'a', 'd' are present in $assoc2 or $assoc3)

echo "Value Differences (array_diff): " . json_encode(array_values($diffValues)) . "
";
echo "Associative Differences (array_diff_assoc): " . json_encode($diffAssoc) . "
";
echo "Key Differences (array_diff_key): " . json_encode($diffKeys) . "
";
?>
How it works: This snippet demonstrates various `array_diff` functions in PHP for comparing arrays. `array_diff()` finds values present in the first array but not in any subsequent array. `array_diff_assoc()` performs a stricter comparison, considering both keys and values. `array_diff_key()` only compares the keys, returning elements from the first array whose keys are not found in the others.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs