Remove an Array Element by Value

As of yet, PHP does not provide an ‘official’ way of removing an array element which is not guaranteed to be at the start (array_shift) or end (array_pop) of the array.

So, after a bit of searching around I found this novel way of removing an element from an array by its value(s) using PHPs array_diff function.

<?php
// initial array
$arr = array("red", "green", "blue", "red", "orange", "yellow");

// remove elements with values "red" or "green"
$arr = array_diff($arr, array("red", "green"));

print_r($arr);
?>

Credit where it’s due goes to Optimus Pete

Comments (0)
+ –