Scooby08 Posted February 1, 2009 Share Posted February 1, 2009 Is there some way to tell which is the last loop from this code: <?php foreach($rows as $row){ echo "$row"; } ?> The amount of loops is always unknown.. Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/ Share on other sites More sharing options...
premiso Posted February 1, 2009 Share Posted February 1, 2009 You can always use a counter like $i++ and count to test. Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/#findComment-751698 Share on other sites More sharing options...
Scooby08 Posted February 1, 2009 Author Share Posted February 1, 2009 ok.. I actually have that sorta thing going, but I'm still not getting how to tell if it's the last loop.. Here is sample code: <?php $amount = "one two three,two three four,three four five,four five six"; $pieces = explode(",",$amount); $i = 1; $data = array(); foreach($pieces as $piece){ $data = explode(" ",$piece); if ($i == 1) { } else if ($i == 2) { } else { echo "<pre>"; print_r($data); echo "</pre>"; } $i++; } ?> Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/#findComment-751699 Share on other sites More sharing options...
premiso Posted February 1, 2009 Share Posted February 1, 2009 $cnt = count($peices); foreach($pieces as $piece){ $data = explode(" ",$piece); if ($i == 1) { } else if ($i == 2) { } elseif ($i == $cnt) { echo 'Last loop!'; }else { echo "<pre>"; print_r($data); echo "</pre>"; } $i++; } Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/#findComment-751702 Share on other sites More sharing options...
.josh Posted February 1, 2009 Share Posted February 1, 2009 If numeric array... foreach ($rows as $key => $row) { if (!$rows[$key+1]) { // this is last loop iteration, do something } // end if } // end foreach If associative array... $count = count($rows) - 1; foreach($rows as $row) { if ($count == 0) { // this is last loop iteration, do something } else { $count--; } // end if...else } // end foreach Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/#findComment-751709 Share on other sites More sharing options...
Scooby08 Posted February 1, 2009 Author Share Posted February 1, 2009 Awesome!! Thanks guys.. Problem solved.. Link to comment https://forums.phpfreaks.com/topic/143323-solved-if-last-loop/#findComment-751711 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.