PHP get index of last inserted item in array

前端 未结 6 1885
没有蜡笔的小新
没有蜡笔的小新 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: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
    

提交回复
热议问题