Rhys
Rhys

Reputation: 1581

Does a PHP array need to be declared before use?

While writing a recent application I accidentally started filling an array before I had declared it.

error_reporting ( E_ALL);  
$array['value'] = 'Test string';

I use E_ALL error reporting and an error was not thrown. Is this correct? And if so, are there any issues with declaring array values whilst never declaring the actual array? Perhaps it just doesn't follow good programming standards.

Upvotes: 9

Views: 2811

Answers (3)

webbiedave
webbiedave

Reputation: 48897

While writing a recent application I accidentally started filling an array before I had declared it.

PHP is a weakly typed language. Your statement:

$array['value'] = 'Test string';

is an implicit declaration (through assignment) of an associative array. So, a notice will not be generated.

However, if you were to write:

echo $array['value'];

before an assigment, then you'll receive an Undefined variable notice.

Upvotes: 7

Viper_Sb
Viper_Sb

Reputation: 1817

To expand on that, no you do not "have" to, but it can be beneficial to.

Also if you have E_NOTICES turned OFF then you will not see errors from an non uninitialized variable. On production you should turn it off, but on development you should turn it ON. It'll allow you to find problems that you might not see.

Upvotes: 4

Matěj Zábský
Matěj Zábský

Reputation: 17272

No, you don't have to

And yes, it is a good habit to declare the array to increase code redability

Upvotes: 5

Related Questions