PHP

Finding Array Differences by Value and Key

Discover how to identify differences between two arrays in PHP using `array_diff()` for values, `array_diff_assoc()` for values and keys, and `array_diff_key()` for keys only.

<?php
$arrayA = ['apple', 'banana', 'orange', 'grape'];
$arrayB = ['banana', 'kiwi', 'apple'];

// Find values in $arrayA that are not in $arrayB
$diffValues = array_diff($arrayA, $arrayB);
echo "Values in A not in B: " . print_r($diffValues, true) . "
";
// Expected: ['orange', 'grape']

$assocA = ['a' => 'red', 'b' => 'green', 'c' => 'blue'];
$assocB = ['a' => 'red', 'b' => 'yellow', 'd' => 'purple'];

// Find values that are in $assocA but not in $assocB (values only, keys are ignored in comparison)
$diffAssocValues = array_diff($assocA, $assocB);
echo "Assoc Values in A not in B (values only): " . print_r($diffAssocValues, true) . "
";
// Expected: ['b' => 'green', 'c' => 'blue']

// Find elements in $assocA that are not in $assocB, considering both key and value
$diffAssocKeyValue = array_diff_assoc($assocA, $assocB);
echo "Assoc Elements in A not in B (key & value): " . print_r($diffAssocKeyValue, true) . "
";
// Expected: ['b' => 'green', 'c' => 'blue']

// Find elements in $assocA whose keys are not in $assocB (keys only)
$diffAssocKeys = array_diff_key($assocA, $assocB);
echo "Assoc Elements in A not in B (keys only): " . print_r($diffAssocKeys, true) . "
";
// Expected: ['c' => 'blue']
?>
How it works: PHP provides several functions to find differences between arrays. `array_diff()` compares array values and returns values from the first array that are not present in any other arrays. `array_diff_assoc()` performs a similar comparison but also takes keys into account, returning elements from the first array whose key-value pair is not found in other arrays. `array_diff_key()` compares only keys, returning elements whose keys are not found in other arrays. These functions are invaluable for comparing lists, configurations, or sets of data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs