Jump to content

Bizzar foreach behavior (skipping)


Firemankurt
Go to solution Solved by mac_gyver,

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?

Edited by Firemankurt
Link to comment
Share on other sites

  • Solution

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.

  • Like 2
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.