PHP 获取数组中最后插入项的索引 [英] PHP get index of last inserted item in array

查看:21
本文介绍了PHP 获取数组中最后插入项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题听起来一样简单;我需要获取最后插入的项目的索引/键.为什么这很困难?请参阅以下两个代码示例:

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
)

简而言之,流行的解决方法 count($array)-1 是有缺陷的.

So in short, the popular workaround count($array)-1 is flawed.

推荐答案

这里有一个 lineara>(最快)解决方案:

Here is a linear (fastest) solution:

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

这篇关于PHP 获取数组中最后插入项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆