note 90492 modified in control-structures.foreach by danbrown

From: Date: Fri, 24 Apr 2009 18:21:56 +0000
Subject: note 90492 modified in control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153694@lists.php.net to get a copy of this message
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. --was-- 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. <? $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. http://php.net/manual/en/control-structures.foreach.php

« previous php.notes (#153694) next »