When we think about printing something in PHP, we think about echo or print and most of the time, in fact all the time that's what we use. But PHP has so many built in functionalities that we might just wonder about it's scalability.
There will be times in our projects when we need to type lot of texts and lengthy sentences and in those times, using echo or print becomes a bit messy and time-consuming as well.
So, in this very short article I'll show you how to write multiple line commands.
To write many lines of code, PHP offers two solutions.
- Just write down all those lines into quotes and print it.
- Use heredoc (multiline sequence using <<< operator)
Let's look at the examples one by one.
The first one, you might have used it many times. Let's see.
//code inside PHP file $author = "Albert Einstein"; echo "I have no special talent. I am only passionately curious. - $author."; //output I have no special talent. I am only passionately curious. - Albert Einstein.
Just put everything in between the quotes and your lines will be printed just fine.
The second one is the one we don't use much.
PHP has multiline sequence functionality which uses <<< operator. It is known as here-document or heredoc.
It is really helpful as it has many advantages. For example,
- It specifies the string literal.
- It keeps the line breaks as it is
- It also keeps the other white spaces and indentation as it is.
Unlike quotes, we can use single and double quotes in heredoc without any constraints, without escaping them with slash().
Let's look at the code.
//code inside PHP file $author = "William Shakespeare "; echo <<<_END Wisely, and slow. They stumble that run fast. - $author. _END; //output Wisely, and slow. They stumble that run fast. - William Shakespeare.
In the code above, as you can see, all we need is <<<_END right after echo and then type everything you want in the output and make sure you leave only requires white spaces and indentation. After that just add _END at the end and you're done.
This code <<<_END and _END tells PHP to print everything between those tags. In other words, it works same as quotes in the first example except that quotes in this code don not need to be escaped.
That means we can write down all those HTML code into PHP using this option and wee can also just replace the dynamic variables and the output will be same.
REMEMBER: Closing the _END; tag must be placed in the new line and nothing should be written in that line, not even comments, not even a single space.
commands multiple line