Jump to content

last in the array


glenelkins

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.