How to find the next numeric index of an existing array?
arrays, php
Solution
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"
}
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.
Problem
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. Example 1: ``` $array = array(); $array[] = 'new index'; ``` This would be 0 for this case. Example 1a: ``` $array = array(100 => 'prefill 1'); unset($x[100]); $x[] = 'new index'; ``` This would be 101 for this case. Example 2: ``` $array = array(-2 => 'prefill 1' ); $array[] = 'new index'; ``` This would be 0 again for this case. Example 3: ``` $array = array(-2 => 'prefill 1', 1 => 'prefill 2' ); $array[] = 'new index'; ``` This would be 2 for this case. 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. 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. Example 4: ``` $array = array(-2 => 'prefill 1', 'str-key-1' => 'prefill 2', 1 => 'prefill 3' , 'str-key-2' => 'prefill 4'); $array[] = 'new index'; ``` This would be 2 for this case again. Example 5: ``` $array = array(-2 => 'prefill-1', 'str-key-1' => 'prefill-2', 1 => 'prefill-3' , '5667 str-key-2' => 'prefill-4'); $array[] = 'new index'; ``` This would be 2 for this case as well. Update: I've added more examples to show some of the edge cases.