1

I tried to find an answer in the original docs of php.net, but I can't found a valid explanation to me. Could you help me in understanding why the node with value 4 disappears in the following code? Thanks in advance,

$ARRAY = [
            "1" =>
                [
                    1, 2, 3
                ],
            4,
            "2" => [
                "2.1" => [ 5, 6, 7 ]
            ]
        ];

echo "ARRAY : <pre>".print_r( $ARRAY, 1 )."</pre><br/>";
2
  • 2
    4 is at index location 1 and you already have that key with an array as value. Hence, this behavior. That being said, numeric keys aren't a good idea for associative arrays due to such issues. Commented Oct 11, 2021 at 9:14
  • 2
    4 gets overwritten by 2 key. Commented Oct 11, 2021 at 9:16

2 Answers 2

4

As stated in the documentation string keys containing valid decimal ints will be cast to int type. This means that "1" and "2" will be casted to 1 and 2 accordingly.

Value 4 comes without a key so PHP will assign it the next integer after the largest key so far (which is 1) so value "4" will be assigned the key 2.

Again as stated in the documentation if you assign multiple values to the same key PHP will keep only the latest value. Now you have two assignments to for key 2 so only the last one will be kept:

1 => [1, 2, 3],
2 => 4, // <- This will be ignored
2 => ["2.1" => [ 5, 6, 7 ]]
Sign up to request clarification or add additional context in comments.

Comments

2

PHP casts purely integer string keys to integer type, so "1" is not different from 1:

var_export(['1' => 'Example']);
array (
  1 => 'Example',
)

PHP also completes missing keys in sequence:

var_export([25 => 'Example', 'No key here']);
array (
  25 => 'Example',
  26 => 'No key here',
)

PHP also allows to have duplicate keys, and the last value overwrites previous ones:

var_export([25 => 'Example', 25 => 'Final value']);
array (
  25 => 'Final value',
)

Taking this into account, it's easy to grasp what's going on: you're inadvertently overwriting key 2.

2 Comments

Thank you guys, for all your responses! It's clear now: I expected a more rigorous management, honestly.
Most rules make sense for a loosely typed language, but the "allow duplicate keys in an array literal" one makes you wonder what the original developer was thinking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.