You Are Here Home > PHP; Advancing Array Pointer In a Foreach Loop

PHP; Advancing Array Pointer In a Foreach Loop

This is not possible because ‘foreach’ operates on a copy of the array so there is no way to do it, don’t waste your time :)

BUT

You can work around this by replacing the ‘foreach’ with a ‘while’ loop, but before you do so, you must know that the following loops are functionally identical:

foreach ($days as $day) {
   echo $day;
}
 
while (list(, $day) = each($days)) {
   echo $day;
}

The same is true for these two, they are functionally identical:

foreach ($days as $i => $day) {
   echo $i .': ' .$day;
}
 
while (list($i, $day) = each($days)) {
   echo $i .': ' .$day;
}

‘While’ doesn’t operate on a copy of the array so you can do something like this, replace your ‘foreach’ with a ‘while’ loop and:

while (list(, $token) = each($tokens)) {
   /* Skip white spaces */
   if ($token == ' ') {
      while ($token == ' ') $token = next($tokens);
   }
}

I hope this makes sense :)

PHP; Advancing Array Pointer In a Foreach Loop
Filed under: PHP, Programming, Web Development   Posted by: Codehead

Got a Question?

Get answers here.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment