Reputation: 12264
So I've got a bit of code that looks like:
$foo[bar]="value 1";
$foo[time]="value 2";
$foo[location]="value 3";
...
I think it should be $foo['bar']="value 1"
instead but I'd like to know why (and the terminology to learn more about this) and why it works if this is "bad code"? What is the danger of leaving the code alone? What are the chances adding the quotes will break something?
Followup/bonus: What about nested arrays?
$colors=array("r"=>"red","b"=>"black","u"=>"blue");
...
$foo[$colors["r"]]="value";
or
$foo["$colors["r"]"]="value";
Here I do want the first one, since I'm using a variable as the key?!
Upvotes: 1
Views: 353
Reputation: 21
bar is the variable and 'bar' is the string. So difference is that, bar can store the value and 'bar' is itself a value. Both will be used as a key in the array $arr. But with bar the array index will vary and 'bar' the key index will be fixed. $arr[bar] can be index or associative whereas $arr['bar'] will be associative array.
Upvotes: 1
Reputation: 21353
As Federico put in the comment. The two means different thing. The one without the quote is a variable. The content of variable bar in $foo[bar] depends on what you assigned it prior. The one with the quote 'bar' is a string whose value is fixed and it will assign 'bar' as the key.
To your question which one and why, it really depends on the scenario, but for most you would probably use the 'bar' version rather than the variable bar version for the following reason:
The only callout with the quote version 'bar' and why it might be bad is because of the nature that the string is hardcoded as a 'bar'. Say you refer this $foo['bar'] in 10 places and one day you decide to change from 'bar' to 'bar1', then you would need to change it in 10 places. Worse, you might only change 9 of them and forgot to change one which introduce a new bug. It is better for the key to become a constant and refer that constant in the code. That way, if you need to change the key name, you could just assign new value to it and all places are updated accordingly. This is generally the rule that at least programming languages that I know follow.
I hope this answer helps.
Upvotes: 3