Menu
Coddy logo textTech

The new line

Part of the Fundamentals section of Coddy's PHP journey — lesson 5 of 71.

If we will echo two statement one after the other, it will print the result in one line. For example:

echo "hello";
echo "world";

This is output:

helloworld

If we want to have a space between them we need to add a space either before the world or after the hello:

echo "hello";
echo " world";

This will also output the same:

echo "hello ";
echo "world";

Now if we want to print them in different line we need to use this symbol: \n. For example:

echo "hello\n";
echo "world";

or we could do it like this: 

echo "hello";
echo "\n";
echo "world";
challenge icon

Challenge

Easy

Create a PHP script that displays a poem with proper line formatting using the newline character.

Write code that outputs the following poem exactly as shown, with each line appearing on a separate line:

Roses are red
Violets are blue
PHP is awesome
And so are you!

Use four separate echo statements to display each line. Make sure each line appears on its own line in the output by using the \n character appropriately.

Cheat sheet

Multiple echo statements print on the same line by default:

echo "hello";
echo "world";
// Output: helloworld

Add spaces manually between words:

echo "hello";
echo " world";
// Output: hello world

Use \n to create a new line:

echo "hello\n";
echo "world";
// Output:
// hello
// world

The newline character can be placed in a separate echo statement:

echo "hello";
echo "\n";
echo "world";

Try it yourself

<?php
// TODO: Write your code below to display the poem using four separate echo statements
// Remember to use \n to create new lines between each line of the poem

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals