What is the different between {$hello}, ${hello} & $hello when use double quotes? - php

I'm a bit confuse with
$hello = "hello";
echo "Say $hello";
echo "Say {$hello}";
echo "Say ${hello}";
and the output is same Say hello. When should I use {$hello} and ${hello}? and why it cannot be used in single quote?

$animal = 'cat';
echo "I have 14 $animals";
This may lead to problems, thus you will "escape" it
echo "I have 14 ${animal}s";
or
echo "I have 14 {$animal}s";
In single caused variables/expression were never substituted.

Single quoted string will never expand variables in PHP. See:
http://php.net/manual/en/language.types.string.php
for more detail of the string formats in PHP. There are 4 in total (including nowdoc introduced in PHP 5.3). Only double quoted and heredoc string formats cause variables to be expanded.

According to http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing ,
this is a simple syntax:
echo "Say ${hello}";
and this is a curly syntax:
echo "Say {$hello}";
Why does them both output the same? Becaus in PHP you can use variable variables in every place you want. For example:
$var = 'somevar';
$bar = 'var';
echo $$bar; // "somevar", simple variable variable
echo ${$bar}; // "somevar", complex syntax
echo ${bar}; // "var", because {bar} treated as a string constant:
// Notice: Use of undefined constant bar - assumed 'bar'
So, using variable variables syntax ${hello} simply translated to $hello.

Related

Printing variables in PHP the difference between these two methods?

I’m learning to program in PHP and I learned that I can print variables with text through different methods but I have a question:
What is the difference between echo $var1 . ' ' . $var2 and echo "{$var1} {$var2}" in PHP? And what to use?
I don’t understand why do we have use curly brackets and even if it is another method what is the difference between the two.
Thank You!
The first method is the concatenation method and is straightforward.
The second method:
you can print variables inside double quotation marks like
echo " $var1 $var2 ";
but what if you want to print something directly b/w, before, or after a variable. e.g:
echo " $var1SomeOtherTextNotFromVariable$var2SomeMoreText ";
PHP will assume that all text as variable until another $ is reached.
To solve this you need to tell PHP where does variable start and end. e.g:
echo " {$var1}SomeOtherTextNotFromVariable{$var2}SomeMoreText ";
Note
Please check Progrock's answer for another benefit of using curly braces.
Per your comment:
No, I know the difference between double quotes and single quotes I just don’t understand why do I need to put curly brackets
You don't "need" curly brackets but they can help in reading your interpolated string.
Please do not do this in your code but consider:
<?php
$hi = 'h';
$hii = 'sh';
echo "$hiie";
Do you get hie or she as the result?
Answer: neither, you get
Notice: Undefined variable: hiie
To fix this then you need to be explicit with one of the following lines:
echo "{$hi}ie"; // hie
echo "{$hii}e"; // she
(Not an answer but worthy of consideration.)
Curlies are useful if you are dealing with arrays:
$foo =
[
'name' => 'Foo',
'age' => 23
];
echo "Name: {$foo['name']}, Age: {$foo['age']}\n";
Output:
Name: Foo, Age: 23
If you omit the curlies you get an error like:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...

I got trouble with eval() function in php?

i have searched this function on google a lot. However, i can't understand this function clearly.
i have a example:
<?php
//eval dangerous to use
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1><?php echo $motto;?><br/>";
echo $str.'<br />'; //result: welcome
eval("?>"." $str"."<?php echo $motto;"); //error
echo $str;
?>
eval() takes a string and evaluates it as PHP code. Here are some important points to note:
eval() takes PHP Code as it's argument -- not mixed HTML markup. Currently, you're passing a string containing HTML markup.
You don't need to add <?php ... ?> tags in the string. eval() already knows the argument is going to be PHP code (it's supposed to be), so you don't need to tell it
Here's a very short example:
$motto = "lksdfasdkf";
$str = 'echo $motto;';
eval($str); // => lksdfasdkf
Here, the string $str contains the literal string echo $motto;, which is a valid statement in PHP. When you call eval($str); the string gets evaluated as PHP code. In this case, it will echo the contents of the variable.
Note that this wouldn't work if you use double-quotes instead:
$motto = "lksdfasdkf";
$str = "echo $motto;";
eval($str);
If you have error reporting enabled, then you'll get the following error:
Notice: Use of undefined constant lksdfasdkf - assumed 'lksdfasdkf' in
The reason is that variables are not parsed when they're wrapped in single-quotes. When you use double-quotes to define your variable, the variable value gets interpolated into the resulting string, meaning $str will contain the literal string echo lksdfasdkf; -- which is not valid PHP code. The solution is to escape the dollar character to avoid it being interpreted as a variable:
$motto = "lksdfasdkf";
$str = "echo \$motto;";
eval($str); // => lksdfasdkf
eval — Evaluate a string as PHP code - your code also working fine
try
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1>$motto<br/>";
echo $str.'<br />'; //result: welcome
eval("\$str = \"$motto\";");
echo $str;

dollar escape? pay me $$owed

I ran into a block of code that executes print with double quotes around the argument. The argument contained a variable that was seemingly escaped by a dollar sign. Is that how a variable is called inside double quotes in php?
print("$$owed");
Here's the full block from the source:
<html>
<head>
<title>Loans</title>
</head>
<body>
<?php
$interest_rate = .14;
function YouOweMe($cost, $interest_rate) {
$weekly_payment = ($cost*$interest_rate);
print "You better pay me $$weekly_payment every week, or else!";
}
<font color="#000000">YouOweMe($cost, $interest_rate);
?>
</body>
</html>
I had to strip the numbers. So annoying.
Anyway, ... What doesn't make sense to me is that $$owed is supposed to, what? Create a new variable from a separate variable that contains a string 'owed'? That doesn't seem practical in any situation. Isn't $$owed just to get a dollar sign before the amount?
Here is an example to understand variable variables :
<?php
$var = "test";
$test = "hey !";
echo "$$var"; //$test
echo "${$var}"; //hey !
echo '$$var'; //$$var
?>
Edited according to comments.
In PHP, a variable is escaped with $ when inside a string defined with double quotes. This does NOT work with single quotes.
$string = "world";
echo "Hello ${string}";
#### outputs "Hello World"
That is how you put a variable into a string (you need the double quotes).
What you have is variable-variable. You can call a variable $foo by using a string with foo in it.
$string = 'foo';
$foo = 'hello world';
echo "I say, ${$string}";
Would output "hello world.
There are a couple of ways to use variables inside double quotes, some common ways are
print("$owed") will print the value of $owed
print("$$owed") is called a "variable variable" (as linked previously)
$owed = "test";
$test = 16;
print("$$owed");
will print out "$test".
Another use of this comes in the form of print("${$owed}"), which takes the value of $test and uses it as the variable name.
I strongly advise you to use single quotes and concatenate the variables needed, as it saves the time for evaluating variables in out, e.g.:
$owed = 42;
print('The value is: ' . $owed);
lg,
flo

Whats the difference between {$var} and $var?

I would like to know when and why should I use {$var}
echo "This is a test using {$var}";
and when (and why) should I use the simple form $var
echo "This is a test using $var";
You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.
http://php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a[1] then the parser needs to
know if you meant to use $a[1] as a
variable, or if you wanted $$a as the
variable and then the [1] index from
that variable. The syntax for
resolving this ambiguity is: ${$a[1]}
for the first case and ${$a}[1] for
the second.
The brackets allow you to remove ambiguity for the PHP parser in some special cases.
In your case, they are equivalent.
But consider this one:
$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello
Without the brackets, you will not get the expected result:
echo "$$foo . 'bar'"; // $foo . 'bar'
For clarity purposes, I would however strongly advise against this syntax.
If you write
echo "This is a test using $vars"
You do not get content of $var in result text.
If you write
echo "This is a test using {$var}s";
Everything will be OK.
P.S. It works only with "" but not for ''.
The {} notation is also useful for embedding multi-dimensional arrays in strings.
e.g.
$array[1][2] = "square";
$text = "This $array[1][2] has two dimensions";
will be parsed as
$text = "This " . $array[1] . "[2] has two dimensions";
and you'll end up with the text
This Array[2] has two dimensions
But if you do
$text = "This {$array[1][2]} has two dimensions";
you end up with the expected
This square has two dimensions.

What's the difference between " and ' when creating strings in PHP?

Very basic, but would like to know the difference/security ramifications etc of using " vs. '.
Can someone provide an example that explains when to use each one?
There are a lot of subtle differences, you'll want to read the php documentation to get a lot of the details, but the important detail are:
Double quotes are parsed whereas single quotes are literals.
You can use variables inline with double quotes, but not with single quotes.
There are some catches though:
<?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
?>
Single quotes are slightly faster.
When a string is enclosed in double quotes, then escape sequences such as \n and variable identifiers such as $var are interpreted.
See the PHP strings manual for specific details and examples.
The biggest one is this. Inside double-quotes, you can include variables, but inside single quotes, the variable name will be literal:
$var1 = "hello";
// this will echo "hello world"
echo "$var1 world";
// this will echo $var1 world
echo '$var1 world';
Using double-quotes becomes extremely useful in a number of situations, expecially when you place {} around the variable names. Here are some examples (certainly others can give you more examples):
// array elements
echo "Element 5 is {$myArray[5]}";
echo "Element 2 subelement 3 is {$myArray[2][3]}";
//
// a dynamic key
$value = "thing";
$someValue = $myArray["some{$value}"]; // returnd $myArray[something]

Categories