RIRedinPA Posted July 15, 2010 Share Posted July 15, 2010 if you have this array: $items = array("item1" => "one", "item2" => "two", "item3" => "three"); and you do a foreach($items as $key => $value) { print $value . "<br>"; //can I get what index I am at in the array within here? } I am trying to determine when I am at the last item Link to comment https://forums.phpfreaks.com/topic/207870-can-you-get-the-index-number-of-an-associative-array/ Share on other sites More sharing options...
wildteen88 Posted July 15, 2010 Share Posted July 15, 2010 Within the foreach loop, you are able to grab the key of the current item using the variable $key. However this will not return the numerical key index of the current item, if you're looping through an associative array that is. What you could do though is first calculate the number of items you have within your array and save this to a variable (ie, $max = count($array)). Then setup a simple counter ($i = 1;) and increment this counter on every loop ($i++). Now to check if the current item is the last one you'll do a simple expression, if($i == $max). If this expression is true you'll know you're on the last item. Example $max = count($array); $i = 1; foreach($items as $key => $value) { print $value . "<br>"; if($i == $max) { // we're at the last item. } $i++; } Link to comment https://forums.phpfreaks.com/topic/207870-can-you-get-the-index-number-of-an-associative-array/#findComment-1086671 Share on other sites More sharing options...
gwolgamott Posted July 15, 2010 Share Posted July 15, 2010 EDIT: Oops he beat me to the punch. Use count() $countend = count($items); $count = 1; foreach($items as $key => $value) { print $value . "<br>"; //can I get what index I am at in the array within here? if($count == $countend){ echo "Last One";} $count = $count +1; } Link to comment https://forums.phpfreaks.com/topic/207870-can-you-get-the-index-number-of-an-associative-array/#findComment-1086674 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.