-1

I've noticed this and am not sure how to work with it.

Basically, it seems PHP magically creates sub-arrays if you use them?

// $moo is not defined
$moo['agagag']['sdfsdf'][] = 4654645;

// no E_NOTICE or anything, it creates the array

// array(
//   'agagag' => array(
//     'sdfsdf' => array(
//       0 => 4654645
//     )
//   )
// )

Is this behavior documented anywhere? Is it safe to use?

(I'm used to creating each level manually, this feels really weird)

2

3 Answers 3

2

Yes, this behaviour is expected and also documented in the manual:

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

Sign up to request clarification or add additional context in comments.

Comments

1

It is save and you can use it but i prefer the following at declaration:

$moo = array(
   'agagag' => array(
       'sdfsdf' => array(
            4654645
        )
    )
);

Comments

0

It is standard behaviour and there's nothing wrong with it: you can look at the full documentation here: http://php.net/manual/en/language.types.array.php (see "Creating/modifying with square bracket syntax").

Of course you must be aware of it in all your code and of course, if you know in advance the structure of the array, you may define it as per @Frankbeen answer,

2 Comments

I've read that section and because this is not explained there, I asked here
In fact, it is explained by this sentence "If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. ". If you can create an array by adding an element to it, i.e. $arr[] = ..., it only makes sense that you can create subarrays as well. P.S. your question is ok; i just pointed the documentation for additional reference.

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.