Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to initialize a php array before using it?

Tags:

php

I am specifically wondering about:

$thisArray = array (
    'bla' => array (
        '4', '5', '6'
    )
);

Could I have just done this instead:

$thisArray['bla'] = array('4', '5', '6');

I can see that it works, but is it consider right and good practice?

like image 666
coderama Avatar asked May 16 '26 20:05

coderama


1 Answers

It's not about "good practice". Both options are valid (and won't produce notices). In first case you're aware about array data and, thus, are able to declare it explicitly with array()

But in common situation you'll not be able to declare array such way - it may be dynamic - it may have different values, it may have different dimensions e t.c. So while both options are valid, second would be used in many common cases where array will hold some data, which content is controlled by application logic.

To say more - almost all sense in having array is - to hold dynamic data which is structured according to your application architecture & logic.

like image 108
Alma Do Avatar answered May 19 '26 10:05

Alma Do