Advancing pointer in a foreach loop


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. 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 :)
  2.  
  3. BUT
  4.  
  5. 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:
  6.  
  7. foreach ($days as $day) {
  8. echo $day;
  9. }
  10.  
  11. while (list(, $day) = each($days)) {
  12. echo $day;
  13. }
  14.  
  15. The same is true for these two, they are functionally identical:
  16.  
  17. foreach ($days as $i => $day) {
  18. echo $i .': ' .$day;
  19. }
  20.  
  21. while (list($i, $day) = each($days)) {
  22. echo $i .': ' .$day;
  23. }
  24.  
  25. ‘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:
  26.  
  27. while (list(, $token) = each($tokens)) {
  28. /* Skip white spaces */
  29. if ($token == ' ') {
  30. while ($token == ' ') $token = next($tokens);
  31. }
  32. }

URL: http://codingrecipes.com/php-advancing-array-pointer-in-a-foreach-loop

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.