Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning array() before using a variable like array

Tags:

arrays

php

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.

like image 365
Tarik Avatar asked Jun 20 '11 06:06

Tarik


1 Answers

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.
like image 89
ThiefMaster Avatar answered Sep 28 '22 16:09

ThiefMaster