Print newline in PHP in single quotes - php

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

Related

Put a document into a php variable with two types of quotes [duplicate]

I am getting a parse error, and I think it's because of the quotation marks over "time". How can I make it treat it as a whole string?
<?php
$text1 = 'From time to "time" this submerged or latent theater in 'Hamlet'
becomes almost overt. It is close to the surface in Hamlet's pretense of madness,
the "antic disposition" he puts on to protect himself and prevent his antagonists
from plucking out the heart of his mystery. It is even closer to the surface when
Hamlet enters his mother's room and holds up, side by side, the pictures of the
two kings, Old Hamlet and Claudius, and proceeds to describe for her the true
nature of the choice she has made, presenting truth by means of a show.
Similarly, when he leaps into the open grave at Ophelia's funeral, ranting in
high heroic terms, he is acting out for Laertes, and perhaps for himself as well,
the folly of excessive, melodramatic expressions of grief.";
$text2 = 'From time to "time"';
similar_text($textl, $text2, $p);
echo "Percent: $p%";
The problem is that I can't manually add \ before every quotation mark. This is the actual text I need to compare.
Use a backslash as such
"From time to \"time\"";
Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';
The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"
As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;
Use the addslashes function:
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
Use htmlspecialchars(). Then quote and less / greater than symbols don't break your HTML tags~
Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"
Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.
$text1= "From time to \"time\"";
or
$text1= 'From time to "time"';
Either escape the quote:
$text1= "From time to \"time\"";
or use single quotes to denote your string:
$text1= 'From time to "time"';
You can use the PHP function addslashes() to any string to make it compatible

single quotes or not in square bracket data?

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.

PHP Both kinds of quotes in variables

I used to know this, but I guess it slipped my mind.
What's the code you put in the beginning and the end of a variable in php to allow both kind of quotes?
The personal rules I follow (not a silver bullet):
If there is no single quotes in the string - use '
If there is single quote(s) in the string - use "
If there are different types of quotes in the string - use ' or HEREDOC
I think you are thinking of heredocs.
Example:
echo <<<EOT
Some text here '' ""'
This should print a capital 'A': \x41
EOT;

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.

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

Categories