note 90492 added to control-structures.foreach
| From: | grobemo at osu1 dot php dot net | Date: | Fri, 24 Apr 2009 18:13:19 +0000 |
| Subject: | note 90492 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153693@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.
<?
$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.
----
Server IP: 208.69.120.35
Probable Submitter: 70.18.46.173
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/90492
Del: integrated -- https://master.php.net/note/delete/90492/integrated
Del: useless -- https://master.php.net/note/delete/90492/useless
Del: bad code -- https://master.php.net/note/delete/90492/bad+code
Del: spam -- https://master.php.net/note/delete/90492/spam
Del: non-english -- https://master.php.net/note/delete/90492/non-english
Del: in docs -- https://master.php.net/note/delete/90492/in+docs
Del: other reasons-- https://master.php.net/note/delete/90492
Reject -- https://master.php.net/note/reject/90492
Search -- https://master.php.net/manage/user-notes.php