简体   繁体   中英

In PHP is there any purpose to defining an array before it is used?

Consider a chunk of php code like this:

$example = array ( 'Location' => 'farm', 'Name' => 'billy', 'Meal' => array());
$example['Meal'] = array('Fruit' = > 'apple', 'Soup' => 'tomato', 'Drink' => 'wine');

Is there any benefit or reason to pre-define the 'Meal' sub array like that beforehand rather than simply writing:

$example = array ( 'Location' => 'farm', 'Name' => 'billy');
$example['Meal'] = array('Fruit' = > 'apple', 'Soup' => 'tomato', 'Drink' => 'wine');

In short, no, unless you intend to examine the $example array between when it's created and when you add the 'Meal' sub-array. In fact, on the 2nd line of your 1st example you're simply overwriting what you originally assigned to it.

You might do it the first way if, for example, you wanted to use Array operations on the sub-array after initially creating $example . But not if you're later going to just overwrite it by assignment.

Not in your case, but if you want to use that variable in an array function like array_push() then it does need to be declared first. It's always best practice to declare it if you know it's going to be an array anyway.

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