Jump to content

Bizzar foreach behavior (skipping)


Firemankurt

Recommended Posts

My foreach loop is skipping an element?

 

How is this possible?

echo '<p>-- Begining of Vardump --</p>
';
var_dump($EventTotals);
echo '
<p>-- End of Vardump --</p>

<p>-- Begining of Just echo --</p>
<p>'.$EventTotals[1]['TITLE'].'</p>
<p>'.$EventTotals[2]['TITLE'].'</p>
<p>-- End of Just echo --</p>

<p>-- Begining of Foreach --</p>
';
foreach ($EventTotals as $DATA);
{

echo '<p>'.$DATA['TITLE']."</p>\n";
}
echo '<p>-- End of Foreach --</p>
'; 

Gives me this output:

<p>-- Begining of Vardump --</p>
array(2) {
  [2]=>
  array(3) {
    ["TITLE"]=>
    string(9) "Book Sale"
    ["TARGETHOURS"]=>
    string(4) "0.00"
    ["HOURS"]=>
    float(4)
  }
  [1]=>
  array(3) {
    ["TITLE"]=>
    string(15) "Spring Jogathon"
    ["TARGETHOURS"]=>
    string(5) "10.00"
    ["HOURS"]=>
    float(7)
  }
}

<p>-- End of Vardump --</p>

<p>-- Begining of Just echo --</p>
<p>Spring Jogathon</p>
<p>Book Sale</p>
<p>-- End of Just echo --</p>

<p>-- Begining of Foreach --</p>
<p>Spring Jogathon</p>
<p>-- End of Foreach --</p> 

Why does the foreach skip one of the elements of the array?  Bug or am I missing something obvious?

Link to comment
https://forums.phpfreaks.com/topic/291443-bizzar-foreach-behavior-skipping/
Share on other sites

Somewhere you have moved the internal index pointer to the last element of the array, which ironically is numbered as 1, while 2 comes before it.  That would mean that you are setting the indexes.  If you need to get both again, you could use reset().

the problem is the ; on the end of the - foreach ($EventTotals as $DATA);

 

edit: what the ; is doing is terminating the foreach() statement. the foreach() is actually looping over all elements of the array, but the {echo ...} isn't part of the loop. when the loop finishes, the  {echo ...} is executed once as inline code and echos what's in $DATA after the last pass through the loop.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.