A strange question about echo output - php

Look at the code below
echo "$_SERVER['HTTP_HOST']";
it show 'Parse error', while the next shows ok
$str = $_SERVER['HTTP_HOST'];
echo "$str";
That was very strange to me.

to refer an associative array inside of a string, you have to either add curly braces or remove quotes:
both
echo "{$_SERVER['HTTP_HOST']}";
echo "$_SERVER[HTTP_HOST]";
would work
http://php.net/manual/en/language.types.string.php <- extremely useful reading

in this case, you should use bracket to point out the variable range in string
echo "{$_SERVER['HTTP_HOST']}";
see also
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

As you have discovered, referring to variables inside a string literal is error-prone and should be avoided. Separate string literals from variables, and use single quotes whenever possible:
echo 'Host: header: ' . $_SERVER['HTTP_HOST'] . "\n";
If you really want to use complex variable expressions inside string literals (and you shouldn't!), remove the inner quotes:
echo "Host header: $_SERVER[HTTP_HOST]";
or surround the variable reference inside curly braces:
echo "Host header: {$_SERVER['HTTP_HOST']}";

If a variable is detected in a double-quoted string, it will automaticly be converted to it's string value. But that's not every your case. the fact that the key of your array is also a string comes in conflict with the php parser. ex :
$ar = array("key" => "val");
echo "$ar['key']"; // won't work
echo "$ar[0]"; // will work because the key is not a string
Anyway, like others already said, the best solution is to encapsulate your variable in curly braces :
echo "{$ar['key']}";

it should be
echo $_SERVER['HTTP_HOST'];
if you want to output $_SERVER['HTTP_HOST'], escape that dollar sign
echo "\$_SERVER['HTTP_HOST']";
or put it into single quote
echo '$_SERVER["HTTP_HOST"]';
Clarification: You should not put only variables into quotes if you want content of actual variable, just delete these quotes and it will work

Related

Send newsletter with php variable in it [duplicate]

Can I echo in single quotes with a variable?
example
echo 'I love my $variable.';
I need to do this because I have lots of HTML to echo too.
You must either use:
echo 'I love my ' . $variable . '.';
This method appends the variable to the string.
Or you could use:
echo "I love my $variable.";
Notice the double quotes used here!
If there's a lot of text, have a look at the Heredoc syntax.
$var = <<<EOT
<div style="">Some 'text' {$variable}</div>
EOT;
The documentation says:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
So the answer is no, not in this way.
The solution is simple:
Don't echo HTML.
As long you are not creating like partial views or stuff †, there is no reason to echo HTML. Embed PHP into HTML instead:
<div class="foo">
<span><?php echo $value; ?></span>
</div>
The benefits are:
Don't have to remember escaping of quotes.
Easier to maintain HTML code.
†: In this case heredoc [docs] is the least worse alternative.
No. Variables (and special characters) only expand in strings delimited with double quotes. If you want to include a variable in a single-quote delimited string, you have to concatenate it instead:
echo 'I love my '.$variable.'.';
You could also escape the double quotes of your HTML if you'd rather use strings delimited by doble quotes:
echo "$text";
See the PHP manual on strings, especially the part on string parsing, for more information.
No. ' will not parse variables. use
echo 'I love my '.$variable.'.';
or
echo "I love my {$variable}. And I have \" some characters escaped";
not within the string, but you can exit the string and concatenate the variable in.
echo 'I love my '.$variable.'.';
The other option would just be to escape the double quotes.
echo "I love my \"$variable\".";
Or just go in and out of php to echo variables (although ugly).
I love my <?php echo $variable; ?>.
With short tags enabled, I love my <?=$variable?>.
Lastly there is heredoc format that allows both single and double quotes along with variables.
echo <<<HTML
I love my $variable. '"...
HTML;
Taken from php.net:
"Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings."
So the answer is no you can't. But you can do it like this :
echo 'I love my' . $variable . '.';
It will be cleaner this way.
Beside the solutions mentioned by other users such as string concatenation, you can use placeholders as follows;
Note the %s is for string.
$variable = 'what ever';
printf('The $variable is %s', $variable);
Try this
<php echo 'I love my '. $variable . ' .'; ?>
In my case, I have changed my command as follows and it worked for me:Added double quotes twice("") beside every single quote(')
PVALUE='1,2,3'
echo "variable='""${PVALUE},repmgr'""" >>postgresql.conf
Output:
variable='1,2,3,repmgr'
#How to print a variable in echo within a single quote bash shell script
use the escape sing-quote to surround the text string as:
variable='my dog'
echo \''I love ' $variable\'
=>
'I love my dog'

Better way to make PHP echo a variable followed by square brackets?

I want PHP to echo a string stored in a variable, immediately followed by a set of square brackets containing some other text. This goes into a form that will be sent back to PHP, so PHP needs to be able to interpret the output of this command as an array item.
Here are the methods I've tried:
$var='string';
echo "string[0]" //works, but only because the variable isn't used
echo "$var[0]"; //PHP tries to treat the string as an array
echo "$var\[0]"; //the slash gets echoed
echo "$var[0\]"; //syntax error
echo "$var"."[0]"; //this is what I'm using now. It's very ugly and I want an alternative
Is there any way to make this work without breaking the string into chunks and concatenating them?
Here are the top-two ways I can think of to do this in a single output statement, the one you choose will end up being what fits your personal preference the most (and there are probably others available as well):
printf('%s[0]', $var);
echo $var . '[0]';
You can use the curly brace syntax. From the PHP manual documentation on Strings:
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {.
Surround the expression within curly braces (like so: {$var}), so PHP knows where the variable begins and ends.
$var = 'foo';
echo "{$var}[0]"; // => foo[0]
This way, you wouldn't have to worry even if the variable was a quoted array index like $var['foo'] either.
Make it explicit where the variable ends with curly brace syntax:
echo "{$var}[0]";

using html and java script tags in php

I am confused about using single and double quotes and back slash while using java script and html tags in php can any one please clarify i googled it but still not clear about it. i am confused for this small thing.i am new to programming
- here is my code
<?php
if(isset($_GET['id'])) {
echo '<div id="d2">';
include "test2.php";
echo '</div>'; }
else
{
echo '<div id="d1">';
include "insert.php";
print "<script type=javascript>"
print "document.getEelementById('alertdiv1').innerHTML='hi' ;"
print "</script>"
echo '</div>';
}
?>
In PHP, you can enclose a string in either single quotes or double quotes. Both are valid:
$var = "this is a string";
$var2 = 'this is also a string';
The main difference is that if your string contains a variable, and you want the variable content to be treated as part of the string, you need to use double quotes:
echo "$var which I made";
will return:
this is a string which I made
When you are manipulating html, css and JavaScript strings, you need to make sure that you don't accidentally close your PHP string. For example:
echo "<h1 class='myheading'>Heading Text</h1>";
Notice how I used double quotes to enclose my string? Because I did that, I was able to use single quotes in the html, without escaping them.
If I'd wanted to use double quotes in my string, I would have had to escape them, like this:
echo "<h1 class=\"myheading\">Heading Text</h1>";
The \ tells PHP that the double quote which immediately follows is to be treated as a literal, and not used to terminate the string.
I can't see any problems relating to quotes in your code.
<script type=javascript> — That is not a valid value of the type attribute (which is optional anyway now). Get rid of the type attribute.
document.getEelementById — Element only has 3 es in it, not 4.
alertdiv1 — There is no element with that id in your code
hi as far as concerned single quotes and double quotes doesnt matters when its a string.but when you use any variable inside
$a = 'hi';
echo '$a' ;
will output
$a
but when you use " "
$a = 'hi';
echo "$a" ;
it will print
hi
Basically, if you're using "" (quotation marks) as your delimiter and you then use a quotation mark as part of the string you must escape it by putting a backslash in front of it.
For example:
$string = "This is my string"; // This is fine as the value of the string doesn't contain any quotation marks (")
$string = "I am including a quote in my string \"To Be Or Not To Be\"."; // This is also fine, as I have escaped the quotation marks inside the string
The same applies if you're using '' (apostrophes) as your delimiter and you then want to use them as part of the string, you must escape them using back slash ().
Hope that helps.
$var = "AAA";
echo 'This costs a lot of $var.'; // This costs a lot of $s.
echo "This costs a lot of $var."; // This costs a lot of AAA.

How can I write a square bracket to a text file in php?

I'm trying to write a php script that will generate a variety of new php pages, but I'm finding that I'm unable to write a square bracket out. When I escape a square bracket in the same way as other characters (ie [ ) the leading \ is written to the new page, which results in code that doesnt work:
echo $row\['Value'\];
When I do not escape the bracket, the page fails, and the same thing happens when I try and substitute asc(91).
I have seen other examples that use code like $row->Value, but I tried that and it didn't work. If anyone can help me output a square bracket, or knows of another method by which I can fetch a value from a row without using one at all, I'd be very grateful
Your echo would appear as an array reference to PHP. Try this:
echo $row, "['Value'];"
assuming that you want the value of $row to be output, and not the literal text $row. If you want the literal text, (e.g. you're trying to build a PHP script on the fly), then either of these should do the trick:
echo '$row[\'Value\'];';
echo "\$row['Value'];";
How about this:
echo sprintf("\$row['%s']", $value); // either scenario
echo sprintf("%s['Value']", $row);
Keep in mind that PHP automatically parses double quote strings ("), and tries to find variabels within. So, the bracket is probably not the issue, the $ variable prefix (coupled with the parser) probably is.
There are a couple other answers that work but I want to elaborate:
The "echo" construct can take a variable or a string. You can't echo a string to the screen in the same way that you do a variable. For example: echo hello; will not behave as you might think. You need to include it in quotes such as echo "hello";
You can also use single quotes. Single quotes and double quotes behave differently. For example:
$foo = "bar";
echo $foo;
echo "$foo";
echo '$foo';
The first will echo "bar", the second will also echo "bar" because PHP looks for variables in double quotes strings. The third will echo '$foo' because PHP does not try to do variable substitution in a single quoted string. So you can do (as #mark-b said):
echo "\$row['Value']";
or
echo '$row[\'Value\']';
Now, that $row->value syntax that you saw, is object notation. It is assuming that $row is an object and not an array. Objects are a whole other ballgame.
You're talking about code generation in your question, so I expect you also want to output the 'echo' statement in the generated code. Assuming you want to save the output into a file so it can be easily executed, you want to use something like fwrite or file_put_contents, I expect. You need to think in terms of strings, which can be a bit tricky when you're seeing code.
Something like this should work:
fwrite($fp, 'echo $row[\'Value\'];'."\n");
Note how the single and double quotes work. \n is resolved to a newline, but anything in the single quotes is treated as a string and is printed as is, apart from \', which should print a literal single quote in the output file.
Hope this helps.

Print newline in PHP in single quotes

I try to use single quotes as much as possible and I've noticed that I can't use \n in single quotes. I know I can just enter a newline literally by pressing return, but that screws up the indentation of my code.
Is there some ASCII character or something that I can type that will produce newline when I'm using single quotes?
No, because single-quotes even inhibit hex code replacement.
echo 'Hello, world!' . "\xA";
echo 'hollow world' . PHP_EOL;
Use the constant PHP_EOL then it is OS independent too.
If you are echoing to a browser, you can use <br/> with your statement:
echo 'Will print a newline<br/>';
echo 'But this wont!';
FYI it is possible to get newlines into strings without double quotes:
printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);
Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.
I wonder why no one added the alternative of using the function chr():
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
The only escape sequence you can use in single quotes is for the single quote itself.
$foo = 'That\'s great';
The only way you could insert a new line into a string created with single quotes is to insert a literal newline
$bar = 'That\'s
cheating';
There IS a difference on using single VS double quotes in PHP
e.g:
1. echo '$var\n';
2. echo "$var\n";
in 1, PHP will print literally: $var\n
in 2, PHP will have to search the location in memory for $var, and return the value in that location, also, it will have to parse the \n as a new line character and print that result
We're in the range of millionths of a second, but there IS a difference in performance. I would recommend you to use single quotes whenever possible, even knowing you won't be able to perceive this performance increase. But I'm a paranoid developer when it comes to performance.
You may want to consider using <<<
e.g.
<<<VARIABLE
this is some
random text
that I'm typing
here and I will end it with the
same word I started it with
VARIABLE
More info at: http://php.net/manual/en/language.types.string.php
Btw - Some Coding environments don't know how to handle the above syntax.
You can use this:
echo 'Hello World' . "\n";
This worked well for me:
print_r('Hello world'.PHP_EOL);
No, according to documentation, PHP recognize no special symbol in single quotes. And there is no single reason to use single quotes as much as possible
in case you have a variable :
$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';

Categories