I wonder if we can do some arithmetic operation, like $x+$y, within a string quote?
// Expected result is:
// 5 + 11 = 16
echo "$x + $y = {$x+$y}"; // Parse error
echo "$x + $y = {$x}+{$y}"; // 5 + 11 = 5+11
echo "$x + $y = ${x+y}"; // 5 + 11 =
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc. Enclosing characters in single quotes ( ' ) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
Enclosing characters in double quotes (' " ') preserves the literal value of all characters within the quotes, with the exception of ' $ ', ' ` ', ' \ ', and, when history expansion is enabled, ' ! '. When the shell is in POSIX mode (see Bash POSIX Mode), the ' !
Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.
No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
I wonder if we can do some arithmetic operation, like $x+$y, within a string quote?
Yes you can. You can just let PHP caclulate the arithmetric operation and then assign it to a variable and output it.
You can also do that inside a double-quoted string (Demo):
<?php
// @link http://stackoverflow.com/a/18182233/367456
//
// Expected result is:
// 5 + 11 = 16
$x = 5;
$y = 11;
echo "$x + $y = ${0*${0}=$x + $y}"; # prints "5 + 11 = 16"
However that is probably not what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With