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:
helloworldIf 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
EasyCreate 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: helloworldAdd spaces manually between words:
echo "hello";
echo " world";
// Output: hello worldUse \n to create a new line:
echo "hello\n";
echo "world";
// Output:
// hello
// worldThe 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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators