Armin
Armin

Reputation: 1756

How to remove elements of an array that match elements in another array

I'd like to write a function that finds matches of all elements within a one-dimensional non-associative array and removes those elements completely from another one-dimensional non-associative array, including the index. Here's an example below.

<?php

function magicfunc($colors, $remove) {
    // some magic here
}

EXAMPLE:

$colors = array(
                'red',
                'green',
                'blue',
                'purple',
                'green',
                'yellow',
                'pink',
                'orange'
            );
$remove = array(
                'green',
                'white',
                'pink'
            );
magicfunc($colors, $remove);

WOULD RETURN:
Array
(
    [0] => red
    [1] => blue
    [2] => purple
    [3] => yellow
    [4] => orange
)

How can I achieve this? Notice how there may be elements that are matched more than once (green), and it's also possible that there are no elements that match a particular one to be removed (white). The function should not have issues with these contingencies.

Upvotes: 0

Views: 181

Answers (1)

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4012

Try array_diff : https://www.php.net/array_diff

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Result:

Array
(
    [1] => blue
)

Upvotes: 2

Related Questions