How to remove an array of items from an array in php?

by ryan.murray , in category: PHP General , a year ago

How to remove an array of items from an array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a year ago

@ryan.murray 

You can remove an array of items from another array in PHP using the array_diff function.


Here's an example:

1
2
3
4
5
6
$array1 = [1, 2, 3, 4, 5];
$itemsToRemove = [2, 4];

$resultArray = array_diff($array1, $itemsToRemove);

print_r($resultArray);


In this example, the array_diff function will compare the elements of $array1 with the elements of $itemsToRemove, and return a new array containing only the elements that are present in $array1 but not in $itemsToRemove.


The output of this code will be:

1
2
3
4
5
6
Array
(
    [0] => 1
    [2] => 3
    [4] => 5
)


Related Threads:

How to remove elements from an array in PHP?
How to remove nan from array in php?
How to remove all same values from an array in php?
How to remove elements from php array?
How to remove elements from php array?
How to remove duplicates in array using PHP?