Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we do some arithmetic operation within double quotes?

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 =
like image 981
weeix Avatar asked Aug 12 '13 07:08

weeix


People also ask

What's the difference between a single quote and a double quote in bash?

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.

What does double quotes do in Linux?

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 ' !

What do single quotes allow in Linux?

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.

What is the escape character for single quote?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.


1 Answers

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.

like image 59
hakre Avatar answered Sep 28 '22 04:09

hakre