0

I have a (probably) very simple and easy to answer question, which I cannot find the answer to anywhere, perhaps it is too simple, and I am not well-versed in php.

I am using a script written by someone else, and they sometimes use single quotes within the square brackets, [ ], and sometimes not. What is the correct way?

For example, is it best written [data] or ['data']? I am a perfectionist and this is driving me crazy to know the proper method.

Echo "Name: " .$ratings['name']."";

$current = $ratings[total] / $ratings[votes]; Echo "Current Rating: " . round($current, 1) . "";

  • This has been covered before, many times. There is no right way, just use whatever coding standard makes sense to you. Personally, I use `'` everywhere, unless I'm dealing with an actual string of text, then it's `"` – Mathew Jan 09 '14 at 00:52
  • 2
    @MatW The question isn't asking about single vs. double quotes - it is asking about single vs. no quotes. – Ken Herbert Jan 09 '14 at 00:54
  • See here: http://stackoverflow.com/questions/13622486/php-array-access-without-quotes - you may get a warning if you have errors turned on. non quoted attempts a constant first. If not found, it reads as a string. proper way would be to avoid errors. I quote them always. – Kai Qing Jan 09 '14 at 00:56
  • And as an extra note you should always be developing with error reporting turned all the way up so you see every tiny thing PHP thinks may be a problem. – Shazbot Jan 09 '14 at 01:38

3 Answers3

1

You must always use single or double quotes when accessing an array element.

I asked in ##php on freenode, and they believe this quirk existed since PHP4.3 (god knows why), but right now when PHP comes across $array[value], it firstly tries to look for a constant named value, and if it is not define()'d, it treats the expression as $array["value"] and spit a Notice in PHP4. In PHP5, this has been upgraded to a warning.

In short: Don't use it. It confuses yourself.

tyteen4a03
  • 1,812
  • 24
  • 45
0

Definitely use the quotes. Additionally, there is a subtle but important difference in PHP between single and double quotes strings. A single quoted string is actually faster, because it is treated as a literal, whereas a double quoted string gets interpreted, which takes O(n) time. Example:

$test = 'world';

echo 'hello\n$test';

yields hello\n$test

$test = 'world';

echo "hello\n$test";

yields

hello

world

Community
  • 1
  • 1
zjm555
  • 781
  • 1
  • 5
  • 14
0

Either double or single would work. Personally I prefer single.

PHP is very forgiving and only spits out a notice if no quotes are given to an index of the array.

raj
  • 819
  • 5
  • 9
  • It's no longer so forgiving with php 7.2, now showing warnings and code will fail with future php versions. – Nikita 웃 Aug 10 '18 at 08:44