Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"next element is already occupied" error

Tags:

arrays

php

When we do something like:

<?php
$arr = array();
$arr[PHP_INT_MAX] = null;
$arr[] = null;

PHP gives the error message:

Warning: Cannot add element to the array as the next element is already occupied in /home/yca/script.php on line 4

Why does the engine say that the next element is already occupied?

Is this a PHP bug?

like image 964
Pacerier Avatar asked Aug 17 '13 06:08

Pacerier


1 Answers

This will literally answer all your questions about arrays in php

Mostly that they are not arrays. They are maps that look like arrays.

http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html

The following I pulled from the current 5.5.2 source:

The internal ulong nNextFreeElement will not increment any more thus giving this error

(the nNextFreeElement is now LONG_MAX which is already occupied)

From the PHP source:

if (zend_hash_next_index_insert(Z_ARRVAL_P(container), &new_zval, sizeof(zval *), (void **) &retval) == FAILURE) {
    zend_error(E_WARNING, "Cannot add element to the array as the next element is already occupied");
    retval = &EG(error_zval_ptr);
    Z_DELREF_P(new_zval);
}

Here is the portion of code that I believe is returning a failure in this case (since the index LONG_MAX is already occupied). In this call the flag = HASH_NEXT_INSERT.

if ((p->nKeyLength == 0) && (p->h == h)) {
    if (flag & HASH_NEXT_INSERT || flag & HASH_ADD) {
        return FAILURE;
    }
    ....
like image 156
Daniel Williams Avatar answered Nov 13 '22 01:11

Daniel Williams