Search code examples
phparraysunsetarray-unset

PHP array unset


Here code (executed in php 5.3.5 and 5.2.13):

$res = array(1, 2, 3);

unset($res[0]);

for($i = 0; $i < sizeof($res); $i++)
{
  echo $res[$i] . '<br />';
}

In results i see

<br />2<br />

Why only one element, and first empty? Can`t understand. When doing:

print_r($res);

See:

Array ( [1] => 2 [2] => 3 )

Thanx for help!


Solution

  • This is because you start with $i = 0; rather than 1 which is the new first index. The last element is missing because it stops before the second (previously third) element since the size has been reduced to 2. This should get the results you wish:

    foreach($res as $value) {
        echo $value . '<br />';
    }