PHP获得数组最后插入项目的索引 [英] PHP get index of last inserted item in array
本文介绍了PHP获得数组最后插入项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是作为标题听起来那么容易;我需要得到最后插入项目的索引/键。这是为什么难?请参见下面的两个code样本:
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>');
写入:
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>');
写入:
res=aaa - 0
res=bbb - 1 <- wrong!
res=aaa - 2 <- wrong!
Array (
[0] => aaa
[2] => bbb <- real key
[3] => aaa <- real key
)
因此,在短期,流行的解决方法计数($数组)-1
是有缺陷的。
推荐答案
下面是一个线性(最快)解决方案:
Here is a linear (fastest) solution:
end($a);
$last_id=key($a);
这篇关于PHP获得数组最后插入项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文