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

by ryan.murray , in category: PHP General , 2 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 2 months 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
)