Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
add comment (requires an account with 50 reputation)

5 Answers

up vote 7 down vote accepted

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 />';
}
share|improve this answer
add comment (requires an account with 50 reputation)

Because after unset sizeof array = 2

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

share|improve this answer
1  
+1 because of mentioning to turn on error_reporting. – MitMaro Mar 25 '11 at 21:36
of course using, thanx! – swamprunner7 Mar 25 '11 at 21:43
add comment (requires an account with 50 reputation)

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.

share|improve this answer
I didn`t know, tnanx! – swamprunner7 Mar 25 '11 at 21:44
add comment (requires an account with 50 reputation)

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 />';
}
share|improve this answer
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.