You Old Fool
You Old Fool

Reputation: 22941

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');

Upvotes: 1

Views: 76

Answers (2)

Madbreaks
Madbreaks

Reputation: 19539

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.

Upvotes: 5

Joao
Joao

Reputation: 2746

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.

Upvotes: 1

Related Questions