Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get index of last inserted item in array

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(); echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>'; echo 'res='.($a[]='bbb').' - '.(count($a)-1).'<br>'; echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>'; die('<pre>'.print_r($a,true).'</pre>'); 

Writes:

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

Sure, that seems to work fine, but see this:

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

Writes:

res=aaa - 0 res=bbb - 1       <- wrong! res=aaa - 2       <- wrong! Array (     [0] => aaa     [2] => bbb    <- real key     [3] => aaa    <- real key ) 

So in short, the popular workaround count($array)-1 is flawed.

like image 420
Christian Avatar asked Jul 18 '10 10:07

Christian


2 Answers

Here is a linear (fastest) solution:

end($a); $last_id=key($a); 
like image 113
romaninsh Avatar answered Sep 17 '22 18:09

romaninsh


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: 0 count: 2 last key: 3 count: 3 last key: foo count: 4 last key: 4 
like image 27
VolkerK Avatar answered Sep 18 '22 18:09

VolkerK