如何找到一个现有的数组的下一个数字索引?

编程入门 行业动态 更新时间:2024-10-21 03:49:06
本文介绍了如何找到一个现有的数组的下一个数字索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在寻找一种简单的方式来获得,将有被选为由PHP以及新元素的数组的下一个数字索引。

I'm looking for a simple way to obtain the next numerical index of an array for a new element that would have been chosen by PHP as well.

例1:

$array = array(); $array[] = 'new index';

这将为这种情况下为0。

This would be 0 for this case.

例1a:

$array = array(100 => 'prefill 1'); unset($x[100]); $x[] = 'new index';

这是101这种情况。

例2:

$array = array(-2 => 'prefill 1' ); $array[] = 'new index';

这将为这种情况下,再次为0。

This would be 0 again for this case.

例3:

$array = array(-2 => 'prefill 1', 1 => 'prefill 2' ); $array[] = 'new index';

这是2这种情况。

我现在想知道下一个数字键的PHP将在阵列中选择,以及为新的元素,但W / O遍历所有的阵列值如果可能的话。

I'd like now to know the next numerical key that PHP would have chosen as well for the new element in the array but w/o iterating over all the arrays values if possible.

我需要这个通过应该模仿,如果新元素添加W / O指定PHP默认行为SPL一个自己的数组实现的偏移量。

I need this for a own array implementation via the SPL that should mimic PHP default behavior if a new element is added w/o specifying the offset.

例4:

$array = array(-2 => 'prefill 1', 'str-key-1' => 'prefill 2', 1 => 'prefill 3' , 'str-key-2' => 'prefill 4'); $array[] = 'new index';

这将为这种情况下再次2。

This would be 2 for this case again.

示例5:

$array = array(-2 => 'prefill-1', 'str-key-1' => 'prefill-2', 1 => 'prefill-3' , '5667 str-key-2' => 'prefill-4'); $array[] = 'new index';

这将为这种情况下是2为好。

This would be 2 for this case as well.

更新:我增加了更多的例子来证明一些边缘情况

Update: I've added more examples to show some of the edge cases.

推荐答案

我不认为必要的信息暴露在PHP脚本。试想一下:

I don't think the necessary information is exposed to PHP scripts. Consider:

<?php $x = array(100 => 'foo'); unset($x[100]); $x[] = 'bar'; var_dump($x); ?> array(1) { [101]=> string(3) "bar" }

有就没有办法知道,101是因为看似空数组的下一个整数,直到加入该项目后。

There would be no way to know that 101 is the next integer given that seemingly empty array, until after adding the item.

如果您是从头开始构建自己的数组类,那么你可以通过一个私有成员变量下一条索引。

If you are building your own array class from scratch, then you could keep track of the next index via a private member variable.

更多推荐

如何找到一个现有的数组的下一个数字索引?

本文发布于:2023-11-30 20:53:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!