Jump to content

Archived

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

glenelkins

last in the array

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
Something like this:
[code]<?php

$array = array("hello", "world", "again");

// loop through array
foreach($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]

Share this post


Link to post
Share on other sites
Heh... I didn't know about end().

Share this post


Link to post
Share on other sites

×

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.