tags:

views:

358

answers:

4

Is there a PHP function to remove certain array elements from an array?

E.g., I have an array (A) with values and another array (B) from which a need to remove values.

Want to remove the values in array A from array B?

+9  A: 

Use array_diff()

$new_array = array_diff($arrayB, $arrayA);

will return an array with all the elements from $arrayB that are not in $arrayA.

To do this with associative arrays use array_diff_assoc().

To remove a single value use:

unset($array[$key]);

You can of course loop that to do the equivalent of the array functions but there's no point in that.

cletus
+1  A: 
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
Time Machine
+2  A: 

The array_diff function will do this for you.

shambleh
+3  A: 

It depends on what you mean by "remove".

You can use the unset() function to remove keys from your array, but this will not reindex it. So for example, if you have:

$a = array(1 => 'one', 2 => 'two', 3 => 'three');

and you then call

unset($a[2]);

You'll end up with something like

(1 => 'one', 3 => 'three');

If you need the array to be sequentially indexed, you can take the unsetted array and feed it into array_values(), which will return a new array with sequentially indexed keys.

Returning to your original scenario, as others observe, array_diff will do the job for you, but note that it doesn't do an index check. If you need that, use array_diff_assoc, instead.

peterb