I would like to know what the advantage of using
curly braces is in the following context:
$world["foo"] = "Foo World!";
echo "Hello, {$world["foo"]}.\n";
is over the following:
$world["foo"] = "Foo World!";
echo "Hello, $world["foo"].\n";
In particular, how is it that the braces resolve any
possible ambiguity in this case (or similar cases)?
Second example will not be parsed. So first is better:)
Anyway, I prefer to use
echo "Hello" . $world["foo"] . ".\n";
Because it is more easy to read to me.
Besides, there is another way:
$world["foo"] = "Foo World!";
echo "Hello, $world[foo].\n";
There no resaons to use one or another. you what you(or your team) like.
See the other answers for the "echo" explanation, but if you're using heredoc, such as the following:
echo <<<EOHTML
<td>{$entity['name']}</td>
EOHTML;
You need the curly braces to properly use the associative array.
Related
Consider thisĀ :
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
This works fine:
php > echo $c[$b[$a]];
w
This also works:
php > echo '$c[$b[$a]]';
'$c[$b[$a]]'
However this leads to a syntax error:
php > echo "$c[$b[$a]]";
PHP Parse error: syntax error, unexpected '[', expecting ']'
While a shorter version works:
php > echo "$b[$a]";
v
Why?
In a double quoted string there are two kinds of variable parsing, simple and complex. Simple parsing will only work with a single dimensional array or object. So these will work:
echo "Valid: $foo[1]";
echo "Valid: $foo[bar]";
echo "Valid: $foo->bar";
But these will not:
echo "Invalid: $foo[1][2]";
echo "Invalid: $foo->bar->baz";
echo "Invalid: $foo->bar()[2]";
Complex parsing is what halfer suggested in his answer, which wraps the expression in curly braces, and will indeed solve your problem:
echo "Valid: ${foo[1][2]}";
echo "Valid: ${foo->bar->baz}";
echo "Valid: ${foo->bar()[2]}";
The short answer is: don't write PHP like this! If it is confusing to read then use an intermediate variable.
However, it can be fixed: it looks like PHP just wants the brace delimiters at the outermost edges of the variable:
<?php
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
echo "{$c[$b[$a]]}";
This is also fine as well:
echo "${c[$b[$a]]}";
In the first case, the whole thing is wrapped in braces, and in the second, the $ is allowed outside of the brace construct to say that the next bit is a variable.
I am using this:
$variable = "Name is \"Bob\"";
$message = <<<EOF
<input type="text" value="$variable">
EOF;
And the result is :
Actually, this is synthetic example and I am working with db. But I tried: this synthetic example works (to simulate problem, actually it shows that what I am doing is not working).
Yes, the quotes will appear in the HTML.
Since the quotes will end the attribute value, you'll make the HTML invalid.
You need to make the variable HTML-safe with htmlspecialchars().
You are generating invalid HTML:
<input type="text" value="Name is "Bob"">
Please use htmlspecialchars() to encode $variable before insertion.
A heredoc is just a convenient shortcut for a multi-line echo. It doesn't care WHAT'S in the string, it'll just be output.
There is NO difference between the following two constructs:
$foo = "A string with an \" embedded quote";
echo <<<EOL
Hello, $foo, how are you
EOL;
echo "Hello, $foo, how are you";
The only real difference is that you don't have escape quotes in the rest of the string:
echo <<<EOL
This is a "quoted phrase" within a sentence
EOL;
echo "This is a \"quoted phrase\" within a sentence";
I'm trying to build a string of HTML as follows:
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed)?'':'disabled'.">";
But it just gives me a parse error (no specific detail, just that this line is the problem).
I've tried various positioning of quotations and brackets but I'm always getting the parse error. Is this possible the way I'm trying?
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed?'':'disabled').">";
Like codingbiz said, this should work with additional parentheses. I'd go for a more readable version with sprintf though:
$html = sprintf(
'<input name="%s" value="%s" size="4"%s>',
GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT,
$MaxCallRecordingTimeSecs,
( $bCallRecordingLicenced ? '' : ' disabled' )
);
Try
".(($bCallRecordingLicensed)?'':'disabled').">";
additional brackets
Try wrapping the whole ternary in parens, rather than just the variable at the start:
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed?'':'disabled').">";
I think its because you change quote marks:
For example
$test = false;
$strings = "hello ".($test?"you":"")." this is a test";
echo $strings;
works as you expected.
I did find that without the brackets round the test, for example, my test only produced the word "you" .. rather than the whole string - which was odd.
I cant get this to work and its driving me mad, pls help
echo "<a href='#' onclick='javascript:$.jGrowl
(\"".$_SESSION['product_description'][$i]."\")' >?</a>";
the problem comes down to the 'product_description' - those single ' marks are breaking it, what should i do sigh
EDIT: if i replace the .$_SESSION['product_description'][$i]. with a bunch of charecters it works, its not a problem with anything but PHP and those ''
Chances are the real problem lies with the $.jGrowl. Within double quotes, PHP tries to parse found variables. e.g.
$foo = 'foo';
echo "This is foo: $foo"; // output: This is foo: foo
So, to avoid this you need to escape the $ using \$ within the string...
echo "...\$.jGrowl..."
See this demo.
Keep this here for reference:
Escape them with a backslash, like you would with double quotes. e.g.
// which ever quote is used to encapsulate the string
// must be escaped within the output.
echo 'Hello, \'world!\''; // output: Hello, 'world!'
echo "Hello, \"world!\""; // output: Hello, "world!"
// but, if you use the opposite quote, it does not need
// to be escaped for output.
echo 'Hello, "world!"'; // output: Hello, "world!"
echo "Hello, 'world!'"; // output: Hello, 'world!'
See the PHP Docs on strings for more information and what characters need escaping.
Are you missing your opening "?
echo "<a href='#' onclick='javascript:$.jGrowl(\"".$_SESSION['product_description'][$i]."\")' >?</a>";
Make it
echo "<a href='#' onclick='javascript:$.jGrowl(\"".$_SESSION['product_description'][$i]."\")' >?</a>";
Try:
echo "<a href='#' onclick='javascript:\$.jGrowl(\"".str_replace('"','\"',$_SESSION['product_description'][$i])."\");' >?</a>";
You need to ensure you are escaping any double quotes within the value...
This one works for me:
echo "<a href=\"#\" onclick=\"javascript:$.jGrowl('".$_SESSION['product_description'][$i]."')\" >?</a>";
can anyone explain to me how to use the curly braces { } in php strings? like
"this is a {$variable}"
"this is a {$user -> getName($variable);} name"
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
Source
It's used to specify the end of the variable name, for example:
$var = "apple";
echo "I love $var!"; //I love apple!
echo "I love $vars!"; // I love !
echo "I love {$var}s!"; //I love apples!
echo "I love ${var}s!"; //I love apples! //same as above
Also the syntax "this is a {$user -> getName($variable);} name" isn't valid. You can't call functions/methods inside of strings. You could however do this:
"this is a " . $user->getName($varaible) . " name"