← Back to all snippets
PHP

Find Value Differences Between Two PHP Arrays

Learn how to compare two or more PHP arrays and identify all values that are present in the first array but not in the subsequent arrays using `array_diff()`.

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

// Values in array1 that are not in array2
$diff1_2 = array_diff($array1, $array2);
echo "Values in array1 not in array2:
";
print_r($diff1_2);

// Values in array1 that are not in array2 or array3
$diff1_2_3 = array_diff($array1, $array2, $array3);
echo "
Values in array1 not in array2 or array3:
";
print_r($diff1_2_3);

$fruitsA = ['a' => 'lemon', 'b' => 'orange', 'c' => 'banana', 'd' => 'apple'];
$fruitsB = ['e' => 'orange', 'f' => 'banana', 'g' => 'grape'];

// With associative arrays, array_diff still compares values
$diffFruits = array_diff($fruitsA, $fruitsB);
echo "
Values in fruitsA not in fruitsB (keys preserved):
";
print_r($diffFruits);
?>
How it works: The `array_diff()` function compares the values of two or more arrays and returns an array containing all values from the first array that are not present in any of the other arrays. It's important to note that this function only compares values, ignoring keys, and it preserves the original keys of the differing elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs