Get last key-value pair in PHP array

前端 未结 9 620
别那么骄傲
别那么骄傲 2020-12-29 01:20

I have an array that is structured like this:

[33] => Array
    (
        [time] => 1285571561
        [user] => test0
    )

[34] => Array
    (         


        
相关标签:
9条回答
  • 2020-12-29 01:48

    If you have an array

    $last_element = array_pop(array);
    
    0 讨论(0)
  • 2020-12-29 01:49

    Another solution cold be:

    $value = $arr[count($arr) - 1];
    

    The above will count the amount of array values, substract 1 and then return the value.

    Note: This can only be used if your array keys are numeric.

    0 讨论(0)
  • 2020-12-29 01:50

    You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:

    $last = end($arr);
    $last = current(array_slice($arr, -1));
    
    0 讨论(0)
  • 2020-12-29 01:51

    try to use

    end($array);
    
    0 讨论(0)
  • 2020-12-29 01:57

    Like said Gumbo,

    <?php
    
    $fruits = array('apple', 'banana', 'cranberry');
    echo end($fruits); // cranberry
    
    ?>
    
    0 讨论(0)
  • 2020-12-29 02:00
    $last = array_slice($array, -1, 1, true);
    

    See http://php.net/array_slice for details on what the arguments mean.

    P.S. Unlike the other answers, this one actually does what you want. :-)

    0 讨论(0)
提交回复
热议问题