获取新插入元素的索引到数组中

问题描述

假设我将元素插入这样的数组中:
$arr[] = \'something\';
如何获得\'something \'的索引? 还有什么其他方法可以将元素插入数组并知道其索引吗?     

解决方法

        尝试end()可以正常工作,
$fruits = array(\'apple\',\'banana\',\'cranberry\');
echo end($fruits); // cranberry
    ,        如果索引中有中断,以下内容将起作用:
$arr = array(\'ASD\',\'QWE\',5 => \'JKL\');
$arr[] = \'ZXC\';
end($arr);
$new_index = key($arr); // 6
    ,        如果您总是插入这样的元素,则索引将为:
count($arr) - 1
您可以插入这样的元素以了解其索引:
$arr[\'somekey\'] = \'something\';
另外,您也可以使用array_search()(http://php.net/manual/en/function.array-search.php),但这可能并不理想,因为您可以在数组中多次使用相同的元素。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...