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. }

2 comments

  1. Andrew Wheal

    You’re missing a close bracket on line 6.

    Also, there is nothing horrible about this code… it is pure awesome!

  2. Thanks – fixed :)

Leave a Reply

Your email address will not be published. Required fields are marked *