Joshua Zollinger
Joshua Zollinger

Reputation: 757

In PHP, how can I find elements in one array that are not in another?

Is there a php function, similar to array_merge, that does the exact opposite? In other words, I have two arrays. I would like to remove any value that exists in the second array from the first array. I could do this by iterating with loops, but if there is a handy function available to do the same thing, that would be the preferred option.

Example:

array1 = [1, 2, 3, 4, 5]
array2 = [2, 4, 5]

$result = array_unmerge(array1, array2);

$result should come out to [1, 3]

Upvotes: 12

Views: 11946

Answers (3)

user2770735
user2770735

Reputation: 11

array_diff

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76666

You can use array_diff() to compute the difference between two arrays:

$array1 = array(1, 2, 3, 4, 5);
$array2 = array(2, 4, 5);

$array3 = array_diff($array1, $array2);
print_r($array3);

Output:

Array
(
    [0] => 1
    [2] => 3
)

Demo!

Upvotes: 37

Srikanth Kolli
Srikanth Kolli

Reputation: 912

 $array1 = array(1, 2, 3, 4, 5);
 $array2 = array(2, 4, 5);
 $result = array_diff($array1, $array2);

Upvotes: 1

Related Questions