Print newline in PHP in single quotes\n


Since
can’t be used with single quotes, we need to resort to other options.

  • When using command line interface, the constant PHP_EOL can be used.
  • When using with browsers, the ‘<br>’ can be used.

Both the options have been demonstrated below.

<?php
if (PHP_SAPI === 'cli') {
   return PHP_EOL;
}
else
{
   return "<BR/>";
}
?>

Suppose our option was not cli, the ‘else’ part will be executed and a newline will be printed −

Example

 Live Demo

<?php
   $var_1 = 'hi';
   $var_2 = "
";    $var_3 = 'hello';    echo $var_1 . $var_2 . $var_3;    echo PHP_EOL;    $var_2 = str_replace("
", '
', $var_2);    echo $var_1 . $var_2 . $var_3;    echo PHP_EOL; ?>

Output

This will produce the following output −

hi hello hi
hello

Updated on: 06-Apr-2020

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements