php to Calculating the Difference Between Two Arrays

In php The array_diff() function calculates this, returning an array with values from the first array that are not present in the second

The array_diff() function identifies values from one array that are not present in others:

$diff = array_diff(array1, array2 [, array … ]);

For example:

$a1 = array(“bill”, “claire”, “ella”, “simon”, “judy”);
$a2 = array(“jack”, “claire”, “toni”);
$a3 = array(“ella”, “simon”, “garfunkel”);
// find values of $a1 not in $a2 or $a3
$difference = array_diff($a1, $a2, $a3);
print_r($difference);

Output

Array(
[0] => “bill”,
[4] => “judy”
);

Example of array_diff

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Output

Array
(
    [1] => blue
)

Leave a Comment