简体   繁体   中英

Creating multidimensional php arrays without declaring

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)

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 (eg 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.

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

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

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM