Jump to content

can you get the index number of an associative array...


RIRedinPA

Recommended Posts

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

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++;
} 

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;
} 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.