Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use array[key] in PHP?

Tags:

Is it okay to use array without single or double quotion like $array[key]? I thought it is bad because PHP look for constant first if I don't use single or double quotation. One of my colleagues told me that it does not matter.

What do you guys think?

like image 717
Moon Avatar asked Mar 08 '10 23:03

Moon


People also ask

Can an array be a key?

No. Arrays can only have integers and strings as keys.

Can an array have same key PHP?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.

What is the main benefit of the array keyword in PHP?

Advantage of PHP ArrayLess Code: We don't need to define multiple variables. Easy to traverse: By the help of single loop, we can traverse all the elements of an array. Sorting: We can sort the elements of array.


1 Answers

It is not considered as OK -- even if it will work in most cases.


Basically, when PHP sees this :

echo $array[key]; 

It will search for a constant, defined with define, called key -- and, if there is none, if will take the 'key' value.


But, if there is something like this earlier in your code :

define('key', 'glop'); 

It will not take

echo $array['key']; 

anymore ; instead, it'll use the value of the key constant -- and your code will be the same as :

echo $array['glop']; 


In the end, not putting quotes arround the key's name is bad for at least two reasons :

  • There is a risk that it will not do what you expect -- which is very bad
    • It might, today...
    • But what about next week / month / year ?
    • Maybe, one day, you'll define a constant with the wrong name ;-)
  • It's not good for performance :
    • it has to search for a constant, before using 'key'
    • And, as said in a comment, it generates notices (even if you disable error_reporting and display_errors, the notices/warnings/errors are still generated, even if discarded later)

So : you should not listen to that guy on this point : he is wrong : it does matter.


And if you need some "proof" that's "better" than what people can tell you on stackoverflow, you can point him to this section of the manual, as a reference : Why is $foo[bar] wrong?

like image 129
Pascal MARTIN Avatar answered Oct 12 '22 22:10

Pascal MARTIN