-1

I recently posted a question in which the code did not work, and was suggested i add apostrophes to my $_POST variables.

I was using

$_POST[variable]

People (?) Recommend

$_POST['variable']

PHP.net Recommends

$_POST["variable"]

What do you use, and why?
What differences arise when using one of the others?

Community
  • 1
  • 1
Lewis Goddard
  • 243
  • 4
  • 20

4 Answers4

1

There is no substantial difference between using " and '. Array keys can be either integers or strings. Strings are quoted in PHP. Not using quotes in this case works, but PHP checks if the key is a constant first, then falling back on interpreting it as a string. Not quoting array keys is discouraged in the PHP documentation.

Gargron
  • 808
  • 7
  • 10
1

The first method will throw a Notice:

[18-Feb-2013 02:46:06] PHP Notice:  Use of undefined constant variable - assumed 'variable' in /Users/Aram/Development/Web/test.php on line 6

Also, you can't have hyphens, as it will treat them separately.

[18-Feb-2013 02:46:56] PHP Notice:  Use of undefined constant variable - assumed 'variable' in /Users/Aram/Development/Web/test.php on line 6
[18-Feb-2013 02:46:56] PHP Notice:  Use of undefined constant name - assumed 'name' in /Users/Aram/Development/Web/test.php on line 6

Use single quotes, since it's simpler than double quotes and doesn't require the use of the shift key.

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
1

It is not about $_POST variables.
It is about strings. Strings as array keys to be strict.

You have strings as array keys here - so, you have to format them as strings.
To format strings, you can use whatever quotes, no difference.

variable without quotes is actually a constant.

The only case where you have to omit quotes is a double-quoted string:

echo "Hello $_GET[name], howdy?";
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

Use $_POST[variable] if variable is the name of a Constant, or a variable: $var.

Use $_POST["variable"] or $_POST['variable'] ifvariable` is a string.

CoursesWeb
  • 4,179
  • 3
  • 21
  • 27