Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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]

like image 951
Joshua Zollinger Avatar asked Sep 12 '13 17:09

Joshua Zollinger


People also ask

How do you check if an array exists in another array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do I check if two arrays have the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

How do you check if an array exists in another array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How can I find the difference between two arrays in PHP?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.


Video Answer


3 Answers

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!

like image 132
Amal Murali Avatar answered Oct 20 '22 14:10

Amal Murali


 $array1 = array(1, 2, 3, 4, 5);
 $array2 = array(2, 4, 5);
 $result = array_diff($array1, $array2);
like image 42
Srikanth Kolli Avatar answered Oct 20 '22 13:10

Srikanth Kolli


array_diff

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

like image 29
user2770735 Avatar answered Oct 20 '22 12:10

user2770735