Quantcast
Viewing latest article 3
Browse Latest Browse All 10

Horribly amazing PHP – check if you’re on the last iteration of a foreach loop

The code is so horrible, it’s gone a full circle and become amazing once again. It’s a method of finding if you’re on the last iteration of a foreach loop. As with anything that uses array pointers in PHP, be careful how you use it as the results may not be as expected:

  1. $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  2.  
  3. foreach ($arr as $a) {
  4.  
  5. // This is the line that does the checking
  6. if (!each($arr)) echo "End!\n";
  7.  
  8. echo $a."\n";
  9.  
  10. }

Viewing latest article 3
Browse Latest Browse All 10

Trending Articles