Computer >> Computer tutorials >  >> Programming >> PHP

Print newline in PHP in single quotes


Since \n 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

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

Output

This will produce the following output −

hi hello hi\nhello