I am going through someone else's code for a very old site and it has a lot of lines like this:
echo '';
I am not familiar with PHP, but having quickly gone through a syntax tutorial, it seems that this command would be printing the contents of the single quotes. However, the single quotes are empty, and there are LOTS of instances like these.
What is the purpose of having these lines, and how did they end up in the code?
You are right, they just print out empty string. I can only guess as to how they got into your code but it is surely safe to delete them.
Single or double quotes are used to denote strings, so with:
echo '';
You are printing empty string essentially nothing.
the only idea i can think of choosing '' vs "" is:
echo '"'; // print "
echo "'"; // print '
Related
I am trying to echo a variable that contains a ', however it broke the script. To fix this, I used addslashes();
This is my code
$row["market_hash_name"] = addslashes($row["market_hash_name"]);
echo $row["market_hash_name"];
Now this doesn't break the script, but displays a backslash. How can i not make it display a backslash before the ' without the ' breaking the script.
Edit: I understand it does not break the script, however, it prevents the rest of the jQuery echoed by the php from working properly.
You can use:
echo htmlspecialchars($row["market_hash_name"], ENT_QUOTES);
It will make sure all special characters are converted to HTML entities, so a single quote becomes '
It won't be breaking, if you are just echoing
$row = array(
'market_hash_name' => "hello'world"
);
echo $row['market_hash_name']; // outputs: hello'world
Echoing the word don't doesn't break your script and you can easily echo it when it is stored in a variable but if you want to echo a word without storing it somewhere it needs to be escaped using htmlspecialchars()
I think you have been confused with query and html output. In a query you escape a string twice. for example:
$query = 'I don\'t think so.';
^ first escape for php script
$query = 'I don\\\'t think so.';
^ second escape for mysql
it goes to mysql like this: I don\'t think so.
Also you can use different types of quotations to avoid this 2 step escaping. like:
"I don't think so.";
'I don"t think so.';
I have a (probably) very simple and easy to answer question, which I cannot find the answer to anywhere, perhaps it is too simple, and I am not well-versed in php.
I am using a script written by someone else, and they sometimes use single quotes within the square brackets, [ ], and sometimes not. What is the correct way?
For example, is it best written [data] or ['data']? I am a perfectionist and this is driving me crazy to know the proper method.
Echo "Name: " .$ratings['name']."";
$current = $ratings[total] / $ratings[votes];
Echo "Current Rating: " . round($current, 1) . "";
You must always use single or double quotes when accessing an array element.
I asked in ##php on freenode, and they believe this quirk existed since PHP4.3 (god knows why), but right now when PHP comes across $array[value], it firstly tries to look for a constant named value, and if it is not define()'d, it treats the expression as $array["value"] and spit a Notice in PHP4. In PHP5, this has been upgraded to a warning.
In short: Don't use it. It confuses yourself.
Definitely use the quotes. Additionally, there is a subtle but important difference in PHP between single and double quotes strings. A single quoted string is actually faster, because it is treated as a literal, whereas a double quoted string gets interpreted, which takes O(n) time. Example:
$test = 'world';
echo 'hello\n$test';
yields hello\n$test
$test = 'world';
echo "hello\n$test";
yields
hello
world
Either double or single would work. Personally I prefer single.
PHP is very forgiving and only spits out a notice if no quotes are given to an index of the array.
This question already has answers here:
single quote inside double quote in php
(3 answers)
Closed 9 years ago.
The below outputs
href="javascript:showBed(" a114:1')'
when I want it on the form
href="javascript:showBed('A114:1')"
in order to get javascript to work. I had a look at this site but coudn't get it to work so I gave up. Perhaps you could give me a hint on how the corrent syntax would be?
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' target='main' class='larmlink'>link</a>");
Thanks =)
Your output is not what it would output, but it is how it would be interpreted (HINT: don't look at a parsed DOM tree, look at the source).
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' ...
==>
echo("<a href=\"javascript:showBed('" . $row['Bed'] ."')\" ...
You really should be using the more standard double quotes around HTML element properties. As such, it is probably best to use single quotes in PHP. I would suggest this:
echo('link');
To print the double-quote character, you can escape it by doing \"
echo("<a href=\"javascript:showBed('" . $row['bed'] ."')\" target='main' class='larmlink'>link</a>");
Live demo
When you want to output variable data to JavaScript, it is good to use json_encode() so that all special characters are escaped automatically. The htmlspecialchars() escapes any values for use in the HTML attribute value.
echo '<a href="',
htmlspecialchars('javascript:showBed(' . json_encode($row['Bed']) . ')'),
'" target="main" class="larmlink">link</a>';
Note that I use single quotes for PHP string literals so that PHP doesn't have to search through my string for a variable to replace. You don't have to do this, but I recommend it.
I like to use sprintf (or printf, but sprintf is easier to refactor) for long strings like this so it's easy to see the template:
echo sprintf("<a href='javascript:showBed(\"%s\")' target='main' class='larmlink'>link</a>", $row['Bed']);
I'd also consider using addslashes on the $row['Bed'] variable in case it has quotes in it.
Using the heredoc syntax often makes code with mixed quotes easier to understand:
echo <<<EOD
link
EOD;
As others mentioned, if the value of your $row['Bed'] might contain single or double quotes, you have to escape it with addslashes.
You can use the heredoc syntax to avoid to escape anything:
echo <<<LOD
link
LOD;
Notice that if your variables contains some quotes you must use the addslashes function or str_replace before.
Another good practive is to separate systematically all the html content from php code:
<a href="javascript:showBed('<?php
echo $row['Bed'];
?>')" target="main" class="larmlink">link</a>
try this one:
echo("<a href='javascript:showBed(\"" . $row['Bed'] ."\")' target='main' class='larmlink'>link</a>");
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.
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>';