PHP get index of last inserted item in array PHP get index of last inserted item in array php php

PHP get index of last inserted item in array


Here is a linear (fastest) solution:

end($a);$last_id=key($a);


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[]='ddd'; foo($a);function foo(array $a) {  end($a);  echo 'count: ', count($a), ' last key: ', key($a), "\n";}

prints

count: 1 last key: 0count: 2 last key: 3count: 3 last key: foocount: 4 last key: 4


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.