PHP get index of last inserted item in array

前端 未结 6 1881
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 05:40

It\'s as easy as the title sounds; I need to get the index/key of the last inserted item. Why is this difficult? See the following two code samples:

$a=array         


        
相关标签:
6条回答
  • 2020-11-29 06:07

    Here is a linear (fastest) solution:

    end($a);
    $last_id=key($a);
    
    0 讨论(0)
  • 2020-11-29 06:10

    On arrays with numeric keys from 0 to n-1 I always use:

    $key = array_push($array, $value)-1;
    

    It doesn't get any faster or simpler I guess. If someone got something like this that works for other arrays please let me know.

    0 讨论(0)
  • 2020-11-29 06:14

    You can use the end() function to get the last element in an array, and array_keys() to return an array of the array-keys. Confusing. In practice, it works like this:

    $key = end(array_keys($array));
    

    Credit goes to hollsk in the comments.

    0 讨论(0)
  • 2020-11-29 06:14

    If you are only working with numerical indexes for your array, the last auto-generated index will always be the biggest array key of the array.

    So, for auto-generated indexes, using something like max(array_keys($a)) should work.

    For example, this :

    $a=array();
    echo 'res='.($a[]='aaa').' - '.(max(array_keys($a))).'<br>';
    echo 'res='.($a[2]='bbb').' - '.(max(array_keys($a))).'<br>';
    echo 'res='.($a[]='aaa').' - '.(max(array_keys($a))).'<br>';
    die('<pre>'.print_r($a,true).'</pre>');
    

    Would get you :

    res=aaa - 0
    res=bbb - 2
    res=aaa - 3
    
    Array
    (
        [0] => aaa
        [2] => bbb
        [3] => aaa
    )
    


    But note that this will not work for situations when you are the one specifying the index...

    0 讨论(0)
  • 2020-11-29 06:18

    You can use key($a) together with end($a)

    $a=array();
    $a[]='aaa'; foo($a);
    $a[3]='bbb'; foo($a);
    $a['foo']='ccc'; foo($a);
    $a[]='ffffd'; foo($a);
    
    function foo(array $a) {
      end($a);
      echo 'count: ', count($a), ' last key: ', key($a), "\n";
    }
    

    prints

    count: 1 last key: 0
    count: 2 last key: 3
    count: 3 last key: foo
    count: 4 last key: 4
    
    0 讨论(0)
  • 2020-11-29 06:31

    Bah, looks like I've found the answer by myself:

    $last_id = array_pop(array_keys($a));
    
    0 讨论(0)
提交回复
热议问题