开发者

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:

pr开发者_开发技巧int_r($res);

See:

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

Thanx for help!


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 />';
}


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.


Because after unset sizeof array = 2

And basicly use error_reporting(E_ALL) for development, it will help you


This is not working as expected because when you unset, so sizeof() returns 2. Thus you are looping on 0 to less than 2(aka 1).

So it will only display the element at index 1, because you unset element at 0.

A simple fix for this would be to use the foreach loop:

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


It is iterating 2 times, the first time through it is accessing index 0, which you've unset, the second time it's accessing index 1, which is what you see outputted. Even though there are only two elements, at index 1 & 2, you're still starting from the original index.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜