PHP Logo

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

Posted by

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:

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

foreach ($arr as $a) {

        // This is the line that does the checking
        if (!each($arr)) echo "End!\n";

        echo $a."\n";

}

2 comments

  1. You’re missing a close bracket on line 6.

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

Leave a Reply

Your email address will not be published.