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.


Solution 1:

Here is a linear (fastest) solution:

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

Solution 2:

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

Solution 3:

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.