PHP Unset Array value effect on other indexes

Oliver Spryn picture Oliver Spryn · Jun 16, 2011 · Viewed 102.7k times · Source

I am working with a PHP loop, and I had one question regarding how unset affects the array keys. This array uses the standard numeric keys assigned by PHP, 0, 1, 2, 3 etc.... Whenever unset() runs on an array value, are the array keys shuffled or are they maintained as before?

Thank you for your time.

Answer

Michael Berkowski picture Michael Berkowski · Jun 16, 2011

The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain.

$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)