Unsetting an element from a PHP array

This is something extremely basic that, for some reason, I find myself looking up every time I need to do it. How do I remove an element from a PHP array?

Perhaps I am overly suspicious but I find myself retesting that this actually works every time I need to do it. To avoid that in the future I am now recording how it is done for posterity.

function printArray($array) {
	foreach($array as $k => $v) {
		echo "$k == $v<br>";
	}
}

$array = array(1 => 'first', 2 => 'second', 3 => 'third');
echo '<br>Array with 3 elements with set indexes<br>';
printArray($array);

unset($array[2]);
echo '<br>After unsetting element with key 2<br>';
printArray($array);

$array = array();
$array[] = 'added string 1';
$array[] = 'added string 2';
$array[] = 'added string 3';

echo '<br>Contents of array without specifying indexes<br>';
printArray($array);
unset($array[1]);
echo '<br>After removing the middle element<br>';
printArray($array);

That code produces the following output.


Array with 3 elements with set indexes
1 == first
2 == second
3 == third

After unsetting element with key 2
1 == first
3 == third

Contents of array without specifying indexes
0 == added string 1
1 == added string 2
2 == added string 3

After removing the middle element
0 == added string 1
2 == added string 3

Note that PHP is clever enough to maintain array indexes when you start unsetting elements even if you didn’t actually specify indexes when you created the array.

Leave a Reply