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.
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: 0 count: 2 last key: 3 count: 3 last key: foo count: 4 last key: 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With