PHP: Simple Method for Removing Values out of an Array CodeUnit 30 MAY 2009

PHPWhile you will quickly learn that adding something to an array in PHP is ridiculously easy, finding a way to remove something turns out not to be quite so easy… well finding the method to remove in any case.

It turns out that removing a value from an array is actually quite simple, and if you really want to be clever about it, ensuring that the array stays exactly in the same state as it was before you removed the offending value as well.

So how do we do it then? Well let’s say we had an array $myarray which contains the values “green”, “blue”, “red” and “yellow”.

To say remove “red” and “yellow” from our array, we would now call:

$myarray = array_merge(array_diff($myarray, array(“yellow”, “red”)));

The result of the above would be a $myarray containing the values “green” and “blue”.

So how did this happen then? Well firstly, we use the PHP function array_diff to compare our $myarray against the new array of “yellow” and “red”, and then to return the difference between the arrays as an array. The follow up step of array_merge then takes the resulting array and should the original have had string indexes declared, ensures that none of the original indexes are changed or moved around incorrectly.

And there you have it. A simple and effective way of removing values from an array.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.