note 90492 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:28:31 +0000
Subject: note 90492 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191964@lists.php.net to get a copy of this message
Note Submitter: grobemo ---- You may want to do something different on the last iteration through a foreach loop. For instance, if you're printing a series of HTML list elements, you may want to add a class like 'last' to the final <li> element. I had trouble finding a good way to do this with a foreach loop. The following code illustrates the method I worked out. <?php $array = array('apples','bananas','cranberries','durians'); $last_item = end($array); foreach($array as $item) { if ($item == $last_item) { print "I like to eat " . $item; } } ?> The foreach loop outputs: 'I like to eat durians'. Technically, you could just use if ($item == end($array)), but I assume that would require more processing time.

« previous php.notes (#191964) next »