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];
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.
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.
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.
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With