Home > Back-end >  php arrays - values that disappear
php arrays - values that disappear

Time:10-11

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/>";

CodePudding user response:

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 ]]

CodePudding user response:

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.

  • Related