It is as simple as the title sounds; I need to get the index / key of the last element inserted. Why is it difficult? See the following two code examples:
$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 )
Of course this works fine, but look at 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 )
In short, the popular workaround count($array)-1 wrong.
arrays php indexing
Christian Jul 18 '10 at 10:05 2010-07-18 10:05
source share