Results 1 to 5 of 5

Thread: second from the end of array

  1. #1
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    2,283
    Thanks
    97
    Thanked 104 Times in 102 Posts

    Default second from the end of array

    I don't have any real need for this, but is there a built in php function that will allow me to get the second value from the end of an array? Sort of like:

    $end=array($arr, -1, 1);
    Last edited by james438; 05-25-2010 at 04:44 AM.
    To choose the lesser of two evils is still to choose evil. My personal site

  2. #2
    Join Date
    May 2007
    Location
    Boston,ma
    Posts
    2,127
    Thanks
    173
    Thanked 207 Times in 205 Posts

    Default

    I've never used this but my guess is

    $inversed = array_reverse($array);
    $end = $inversed[1];

    http://php.net/manual/en/function.array-reverse.php
    Corrections to my coding/thoughts welcome.

  3. The Following User Says Thank You to bluewalrus For This Useful Post:

    james438 (05-25-2010)

  4. #3
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    2,283
    Thanks
    97
    Thanked 104 Times in 102 Posts

    Default

    Not exactly what I was looking for, but works just the same .
    To choose the lesser of two evils is still to choose evil. My personal site

  5. #4
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    echo $array[count($array)-2];

    (We subtract 2 because count returns a count from 1+ and array indexes range from 0+.)

    BTW, this will return two errors (undefined index notice; error count's value is not an array) if you use it on a non-array or on an empty array. Check that first.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  6. The Following User Says Thank You to djr33 For This Useful Post:

    james438 (05-25-2010)

  7. #5
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    2,283
    Thanks
    97
    Thanked 104 Times in 102 Posts

    Default

    nice, thanks for those answers. I was looking for something really simple like the answers you both gave.
    To choose the lesser of two evils is still to choose evil. My personal site

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •