PHP
Find the Difference Between Two Arrays (Values Only)
Discover how to identify values present in the first array but not in subsequent arrays using PHP's `array_diff()` function, useful for data comparison.
<?php
$array1 = ['apple', 'banana', 'orange', 'grape'];
$array2 = ['banana', 'grape', 'kiwi'];
$difference = array_diff($array1, $array2);
print_r($difference);
// Expected Output: Array ( [0] => apple [2] => orange )
$newItems = ['pencil', 'pen', 'eraser'];
$oldItems = ['pen', 'book', 'paper'];
$itemsToAdd = array_diff($newItems, $oldItems);
print_r($itemsToAdd);
// Expected Output: Array ( [0] => pencil [2] => eraser )
?>
How it works: The `array_diff()` function compares `array1` against one or more other arrays and returns the values in `array1` that are not present in any of the other arrays. It's case-sensitive and only compares values, ignoring keys. This is invaluable for tasks like identifying new items, removed items, or discrepancies between two lists of data.