You Are Here Home > PHP; Advancing Array Pointer In a Foreach Loop
DirectorySync is a directory synchronizing and backup utility providing automated, real-time syncing and scheduled, configurable backups at an affordable price.

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’ used this way with ‘each’ 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
Do you have any questions? ask here.




1 Comment »

  1. Matt:
     

    You’re the man! This is exactly what I needed! I was pulling my hair out for hours trying to figure out why key($_POST) inside a foreach loop wasn’t working correctly. Your suggestion above fixed it pronto. Thank you!

    Comment

RSS feed for comments on this post. TrackBack URL

Leave a comment