Jump to content


Photo

last in the array


  • Please log in to reply
3 replies to this topic

#1 glenelkins

glenelkins
  • Members
  • PipPipPip
  • Advanced Member
  • 760 posts
  • LocationBridlington - East Riding of Yorkshire - United Kingdom

Posted 08 May 2006 - 05:30 PM

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

foreach ($array as $array2) {
    if ($array2 is the last record) {
        echo "last record";
    } else {
        echo $array2;
    }
}

http://thewebsolutionprovider.com - A Solution For Everything Web!

#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 08 May 2006 - 05:40 PM

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).

Info: PHP Manual


#3 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 08 May 2006 - 05:50 PM

Something like this:
<?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
    }
}
?>


#4 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 08 May 2006 - 06:08 PM

Heh... I didn't know about end().

Info: PHP Manual





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users