5

I tried to find a proper and explanatory title but I couldn't and I will try to explain what I am asking here:

Normally if you don't assign an empty array to a variable, you can start assign values to indexes like this:

$hello["world"] = "Hello World";
...
echo $hello["world"];

but I always encounter such definition:

$hello = array() //assigning an empty array first
$hello["hello"] = "World";
...
echo $hello["hello"];

Why is it used a lot. Is there a performance gain or something with the second one?

Thanks.

3
  • 1
    Oh god, is the first really valid? I'm always discovering new reasons to hate PHP... Commented Jun 20, 2011 at 6:06
  • Yeah, as long as PHP engine the indexes, it interprets it as arrays. You don't have to use array() to declare something is array. Commented Jun 20, 2011 at 6:09
  • 1
    The latter is a good practice, it prevents another coder from guessing OK so may be $hello is declared somewhere else, may be in another file. Commented Jun 20, 2011 at 6:12

4 Answers 4

7

Two reasons:

  • Better readability (you know the array is initialized at this point)
  • Security - when running on a system with register_globals enabled a user could add e.g. hello[moo]=something to the query string and the array would already be initialized with this. $hello = array(); overwrites this value though since a new array is created.
Sign up to request clarification or add additional context in comments.

Comments

4

Initializing your variables is good practice.
Take for example this:

$foo = 'bar';

// 10 lines and 1 year later
$foo['baz'] = 'test';

Congratulations, you now have the string "tar".

This may happen accidentally and introduce needless bugs. It gets even worse with conditional variable creation. It's avoided easily by getting into the good habit of explicitly initializing your variables.

Comments

3
$hello = array();

if(someConditionIsTrue){
    $hello["world"] = "Hello World";
}

foreach($hello as $val){     // this will not give you any error or warning.
   echo $val;     
}

But

if(someConditionIsTrue){
    $hello["world"] = "Hello World";
}

foreach($hello as $val){     // this will give you error .
   echo $val;     
}

Comments

2

If I remember correctly, the first one will produce a warning by PHP if you have error_reporting as E_ALL. You should always use the second method because it explicitly initialises a new array. If you are looking through code and out of nowhere see $hello["hello"] but cannot recall seeing any reference to $hello before, it would be confusing.

The same will happen if you do $hello[] = "World", a warning will be displayed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.