Get last key-value pair in PHP array

前端 未结 9 621
别那么骄傲
别那么骄傲 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 02:03

    Example 1:

    $arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
    print_r(end($arr));
    

    Output = e


    Example 2:

    ARRAY without key(s)

    $arr = array("a", "b", "c", "d", "e");
    print_r(array_slice($arr, -1, 1, true));
    // output is = array( [4] => e ) 
    

    Example 3:

    ARRAY with key(s)

    $arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
    print_r(array_slice($arr, -1, 1, true));
    // output is = array ( [lastkey] => e ) 
    

    Example 4:

    If your array keys like : [0] [1] [2] [3] [4] ... etc. You can use this:

    $arr = array("a","b","c","d","e");
    $lastindex = count($arr)-1;
    print_r($lastindex);
    

    Output = 4


    Example 5: But if you are not sure!

    $arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
    $ar_k = array_keys($arr);
    $lastindex = $ar_k [ count($ar_k) - 1 ];
    print_r($lastindex);
    

    Output = lastkey


    Resources:

    1. https://php.net/array_slice
    2. https://www.php.net/manual/en/function.array-keys.php
    3. https://www.php.net/manual/en/function.count.php
    4. https://www.php.net/manual/en/function.end.php
    0 讨论(0)
  • 2020-12-29 02:09

    As the key is needed, the accepted solution doesn't work.

    This:

    end($array);
    return array(key($array) => array_pop($array));
    

    will return exactly as the example in the question.

    0 讨论(0)
  • 2020-12-29 02:11

    "SPL-way":

    $splArray = SplFixedArray::fromArray($array);
    $last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);
    

    Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.

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