Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a linear (fastest) solution:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...