John Davidson

php - Inserting a value into an array gives it a negative index

0 comments
Message:


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?



My Answer:
first
[-6] = second
[0] = third
_)

Rate this post

3 of 5 based on 5048 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us