Home > Mobile >  Inserting a value into an array gives it a negative index
Inserting a value into an array gives it a negative index

Time:10-28

For some reason, in one environment, when I insert a value into an array, it pushes with a negative index. The 'original' and 'newOne' are just to show how I am manipulating the array before getting to the weird part, I'm not sure if this is related to the problem:

$original = [];
$original[-7] = 'first';
$original[-6] = 'second';

$newOne = [];

$newOne = $original   $newOne;

$newOne[] = 'third';

printing this:

Array
(
    [-7] => first
    [-6] => second
    [-5] => third
)

In another environment and in 3 different online PHP websites that I tested, the code above would work out as expected, printing:

Array
(
    [-7] => first
    [-6] => second
    [0] => third
)

In those online PHP websites I've tested from PHP 5.6 to 8.1 and the result was aways this.

My question is: Why does the index from $newOne[] = 'third'; becomes -5, when it should always be 0?

CodePudding user response:

I created by own code and ran it in various PHP versions:

$original = [-7 => 'first',
             -6 => 'second'];

$original[] = 'third';

print_r($original);

The result might be of interest to you. Output for 8.0.1 - 8.0.25, 8.1.0 - 8.1.12, 8.2rc1 - rc3 is:

Array
(
    [-7] => first
    [-6] => second
    [-5] => third
)

and the output for 7.4.0 - 7.4.32 is:

Array
(
    [-7] => first
    [-6] => second
    [0] => third
)

See: : https://3v4l.org/a0GJj

A very short answer to your question would therefore be that the question is wrong. The code that you say results in the -5 key isn't actually the code that you run.

PHP 8.0 changed how it increments negative numeric array keys. The thing you see in the above example has been documented here: PHP 8.0: Implicit negative array key increments do not skip negative numbers

  • Related