Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to find the next numeric index of an existing array?
    primarykey
    data
    text
    <p>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.</p> <p><strong>Example 1:</strong></p> <pre><code>$array = array(); $array[] = 'new index'; </code></pre> <p>This would be 0 for this case.</p> <p><strong>Example 1a:</strong></p> <pre><code>$array = array(100 =&gt; 'prefill 1'); unset($x[100]); $x[] = 'new index'; </code></pre> <p>This would be 101 for this case.</p> <p><strong>Example 2:</strong></p> <pre><code>$array = array(-2 =&gt; 'prefill 1' ); $array[] = 'new index'; </code></pre> <p>This would be 0 again for this case.</p> <p><strong>Example 3:</strong></p> <pre><code>$array = array(-2 =&gt; 'prefill 1', 1 =&gt; 'prefill 2' ); $array[] = 'new index'; </code></pre> <p>This would be 2 for this case.</p> <p>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.</p> <p>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.</p> <p><strong>Example 4:</strong></p> <pre><code>$array = array(-2 =&gt; 'prefill 1', 'str-key-1' =&gt; 'prefill 2', 1 =&gt; 'prefill 3' , 'str-key-2' =&gt; 'prefill 4'); $array[] = 'new index'; </code></pre> <p>This would be 2 for this case again.</p> <p><strong>Example 5:</strong></p> <pre><code>$array = array(-2 =&gt; 'prefill-1', 'str-key-1' =&gt; 'prefill-2', 1 =&gt; 'prefill-3' , '5667 str-key-2' =&gt; 'prefill-4'); $array[] = 'new index'; </code></pre> <p>This would be 2 for this case as well.</p> <p>Update: I've added more examples to show some of the edge cases.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload