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"
Related
I am playing around with wordpress and wondering, why this line of code works:
echo "<a href='....'>$name</a>";
I learned it this way:
echo "<a href='....'>".$name."</a>";
Is there something special defined in WP to make this work?
In PHP, there are two types of String.
The first type uses the single quotes, as follows.
$val = 'this is a simple string';
The second type is as follows:
$val = "This is a not so simple string";
With the latter type, any variables included in the string will be resolved to their values, so:
$val = "Hello there";
$message = 'Dave says $val';
// Literally equals: Dave says $val
$message2 = "Dave says $val";
// Literally equals: Dave says Hello there
There are lots of other differences, which you can read about here.
I have a PHP function that in echoing out a string, is losing some of the characters passed in it. Any reason why this would be happening?
I pass: $vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX
It returns: #jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX
This is my PHP code:
<?php
function display($str) {
echo $str;
}
display("$vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX");
?>
If you have $ in you string use single quotes:
display('$vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX');
Otherwise PHP would try to use $vhkvdov as a variable name and replace it by its contents, what will be nothing as I expect that the variable is not set
PHP reference on strings
Note: During development I would set error_reporting in php.ini to
error_reporting=E_ALL | E_NOTICE;
and
display_errors=On
or
log_errors=On
error_log=PATH/TO/YOUR/LOG.file ; make sure this is writable by the web server
To see an error message like :
PHP Notice: Undefined variable: vhkvdov in
The problem is that you are using double quotes, which make PHP interpret the inner string for PHP variables.
Consider the following example:
$friend = "foo";
echo "hello $friend";
// Output: hello foo
Use single quotes instead if you do not want PHP to interpret the string contents.
$friend = "foo";
echo 'hello $friend';
// Output: hello $friend
Take a read of this to help clarify why this is happening:
http://php.net/manual/en/language.types.string.php
Specifically:
When a string is specified in double quotes or with heredoc, variables
are parsed within it.
This is whats happening with your code:
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.
Here is an example:
<?php
$juice = "apple";
echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>
The above example will output:
He drank some apple juice.
He drank some juice made of .
When you use single quotes, you will avoid this issue as the string taken litterally:
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
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.
I have Learnt that Quotes doesn't matter in PHP.
But in the following code, if I try to use single quotes in eval(); I get error, on the other hand code works fine with Double Quotes.
$a = '2';
$b = '3';
$c = '$a+$b';
echo $c.'<br/>';
eval("\$c = \"$c\";");
//eval('\$c = \'$c\';'); //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
echo $c;
PHP.net says that escape sequences are not expanded when using single quotes.
Quotes do matter ;-)
<?php
$color = "red";
echo "My car is $color"; // Outputs "My car is red"
echo 'My car is $color'; // Outputs "My car is $color"
?>
Unlike double quotes, PHP does not parse variables in single quotes.
Example:
$name = 'John';
echo 'hello $name'; // hello $name
echo "hello $name"; // hello John
More Information
FYI, it isn't good idea to use eval in production environment for security reasons.
Using eval is a bad idea but if you are doing this for learning purpose then the correct way is
eval("\$c = \$c;");
.
don't use eval and update your string-quoting skills here:
The following example was lifted from: The PHP Manual
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
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>";