Removing values from a PHP array

Note to self: here follows the easiest way of removing an item from a PHP array. As I see it, there’s three main ways to remove an item, knowing the key, from a PHP array and preserve keys.

array_slice() around it

Firstly, the most conceptually awkward, hardest to think up and most difficult to code is the first method I thought of. You have an array with an item somewhere in it. By taking all the values on side of the item using array_slice(), and all the values the other side of it, then joining them together, you have yourself a new array with all the values except for the one you wanted to remove. Perfect. But. It’s a complicated function, and you’re calling it twice for a task that should be able to be done by a simpler function.

array_splice() it out

array_splice() is the closest single function to a fantasy array_remove(). It allows you to remove any number of items, required you know the offset (not the key, the offset, see the PHP manual notes for more information) of the item you want to start removing from. It’s very flexible, allowing negative lengths, negative offsets and all the variants on kitchen sinks you could imagine. Flexibility = processing time, and of course it’s a fairly slow function. So again, not ideal.

unset() the value and re-assign indices

The best route is to unset() the value you want. That is sometimes the end of the tale, except unset()ing leaves a hole in your index list. Example:

$ar = array (
	1 => 'blah',
	2 => 'blah'
	3 => 'blah'
/* $ar is now:
Array (
	1 => 'blah',
	3 => 'blah'
As you can see, the index '2' is missing from the array. */

Not to fear, this hole is easily fixed with a quick shuffle courtesy of array_values(). One call to that, $ar= array_values($ar); reassigns your indices so that you have a nice list again.

Hope that helps someone.