Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does php throw syntax error in code

Tags:

php

echo "<input  type=\"text\" size=3 name=\"{$item[\"name\"]}\"/>";

but following works fine

echo "<input  type=\"text\" size=3 name=\"{$item['name']}\"/>";

As per my understanding \" really escape the "

like image 234
David Avatar asked Jun 27 '26 15:06

David


2 Answers

You don't need to escape the quotes inside the {}. That's supposed to be quoted because it means the string index "name" for the PHP array $name. Without quotes (or escaped quotes), name is treated as a constant (which I'm assuming it isn't), and then you've got an extra pair of quotes which don't belong.

OTOH, this would also be correct:

echo "<input  type=\"text\" size=\"3\" name=\"$item[name]\"/>";

(no quotes around name and no {} either)

see http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing


re:comment

Any non-keyword without quotes or the $ sign is regarded as a constant (as you can define with the define function), thus "name" (with quotes) is a string, and name without quotes is a constant.

when written like this, however:

echo "{$item[name]}";

PHP will first look for a constant with the name name, then if it doesn't exist, it will use the string "name". However, it will (depending on your settings?) also issue a warning.

like image 132
mpen Avatar answered Jun 29 '26 05:06

mpen


Why use " anyway? It turns PHPs special character parsing on, eats more processor time. It is better practice to use '.

This way you don't have to escape all HTML quotation marks so the script will be nicer, shorter and less processor will used for simple text processing, where you just join text with a variable.

echo '<input  type="text" size=3 name="'.$item['name'].'"/>"';
like image 42
Ákos Nikházy Avatar answered Jun 29 '26 05:06

Ákos Nikházy