Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values from one array which do not exist in another array?

Tags:

How to get the values from an array that are NOT in another array in PHP?

My current aproach have bad time complexity. Is there an inbuilt php function that can solve my problem?

Example:

$a1 = array(1,2,3,4); $a2 = array(3,4,5,6,7); 

Result:

[5,6,7]; 
like image 264
Vinoth Babu Avatar asked Jun 19 '13 07:06

Vinoth Babu


People also ask

How do you get the elements of one array which are not present in another array using Javascript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.

How to match 2 arrays in PHP?

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

How to get different value from two array 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.

How do you find the only value in an array?

Getting the only values from an array To extract the only values from an associative array, we use array_values() function, it returns a new arrays with numeric indexes (starting from 0 index) and values. Syntax: array_values(array); It accepts an array and returns a new array having only values from given array.


1 Answers

array_diff is your friend.

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

$a1 = array(1,2,3,4); $a2 = array(3,4,5,6,7); $result = array_diff($a2, $a1);    print_r($result); Array (     [2] => 5     [3] => 6     [4] => 7 ) 
like image 141
Hanky Panky Avatar answered Sep 23 '22 23:09

Hanky Panky