Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 300
swamprunner7 Avatar asked Apr 17 '26 05:04

swamprunner7


2 Answers

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 />';
}
like image 91
tvkanters Avatar answered Apr 18 '26 20:04

tvkanters


PHP doesn't rearrange the keys on unset. Your keys after the unset are 1 and 2. In the for cycle, i gets the 0 and 1 values. Using this snippet you should init i to 1, the first key of the array.

Hint 1: Use foreach to itearate over an array.
Hint 2: Don't use aliases. Use count instad of sizeof.

like image 33
erenon Avatar answered Apr 18 '26 20:04

erenon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!