glenelkins Posted May 8, 2006 Share Posted May 8, 2006 is there a simple way to tell if my loop on an array is looking at the last record in the array? or is the only way to use a counter?example code[code]foreach ($array as $array2) { if ($array2 is the last record) { echo "last record"; } else { echo $array2; }}[/code] Quote Link to comment https://forums.phpfreaks.com/topic/9322-last-in-the-array/ Share on other sites More sharing options...
ober Posted May 8, 2006 Share Posted May 8, 2006 You're going to have to use a counter of some kind, but count($array_name) will give you the number of items in the array (starting at 1, the indexes of the array start at 0). Quote Link to comment https://forums.phpfreaks.com/topic/9322-last-in-the-array/#findComment-34350 Share on other sites More sharing options...
wildteen88 Posted May 8, 2006 Share Posted May 8, 2006 Something like this:[code]<?php$array = array("hello", "world", "again");// loop through arrayforeach($array as $key){ // check that the current value $key is equal to the last value in the arrray if($key == end($array)) { echo "end of array! - " . $key . "<br />\n"; // end of array } else { echo "array is at key " . $key . "<br />\n"; // not end of array }}?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/9322-last-in-the-array/#findComment-34355 Share on other sites More sharing options...
ober Posted May 8, 2006 Share Posted May 8, 2006 Heh... I didn't know about end(). Quote Link to comment https://forums.phpfreaks.com/topic/9322-last-in-the-array/#findComment-34359 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.