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]
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.
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.
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.
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.
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!
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(2, 4, 5);
$result = array_diff($array1, $array2);
array_diff
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
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