如何找到一个现有的数组的下一个数字索引? [英] How to find the next numeric index of an existing array?

查看:146
本文介绍了如何找到一个现有的数组的下一个数字索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种简单的方式来获得,将有被选为由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.

这篇关于如何找到一个现有的数组的下一个数字索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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