SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    Probably eating pie mitsubishi's Avatar
    Join Date
    Sep 2001
    Location
    England, UK
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Highest value of an array key?

    Doesn't actually matter now as I've fetched it while building the array, but... Isnt there a function for finding the maximum value of a key in a numeric array? In a numeric array are the keys ordered numerically and not the order in which they were set? I tried imploding array_keys() and sending that to max(), but PHP doesn't like that idea. I know you can cycle through and test each against the current max, but there must be something more elegant..?

  2. #2
    SitePoint Enthusiast Goldfinger's Avatar
    Join Date
    Dec 2001
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you could always you sort the array by the key then grab the last key....

  3. #3
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you are just manually assigning entries to an array with something like.

    PHP Code:
    while (.....) {
      
    $data[] = $row;
      } 
    Then

    PHP Code:
    $maxkey count($data) - 1

    $maxkey would hold your max key value.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  4. #4
    SitePoint Wizard Chris82's Avatar
    Join Date
    Mar 2002
    Location
    Osnabrück
    Posts
    1,003
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi!

    This worked for me:

    PHP Code:
    <?php
    $test 
    = array("1" => "test""5" => "bla""3" => "blubb");

    echo 
    max(array_keys($test));
    ?>
    It should also work for keys that are non-numeric.

  5. #5
    SitePoint Wizard silver trophy redemption's Avatar
    Join Date
    Sep 2001
    Location
    Singapore
    Posts
    5,269
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yet another alternative : use ksort() to sort the array by key then get the first element
    PHP Code:
    $sorted_array=ksort($my_array);
    $max_key=$sorted_array[0]; 

  6. #6
    Probably eating pie mitsubishi's Avatar
    Join Date
    Sep 2001
    Location
    England, UK
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cheers for the input guys, I'm assuming that as 2 of suggested sorting the array that even in numeric arrays they remain in set order. I'm manually assigning keys in the while loop so count() is no good for me.

    Chris, I didn't know you could send an array to max(), so I tried
    Code:
    $keys = implode (', ', array_keys($array));
    $max = max($keys);
    But you can't use a string.


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
  •