5

In most languages, I have to initialize an associative array before I can use it:

data = {}
data["foo"] = "bar"

But in PHP I can just do

data["foo"] = "bar"

Are there any repercussions to doing this? Is this "the right way" to write PHP?

4

2 Answers 2

2

Is the same, but is not a good idea, the next is a copy-paste from php documentation.

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

Sign up to request clarification or add additional context in comments.

Comments

0

Basically it's the same, and no you won't find any problem or repercussion.

But if you like you can do this:

$a = array();

You can read more in the PHP page

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.