Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print newline in PHP in single quotes
In PHP, the newline character doesn't work inside single quotes because single quotes treat all characters literally. However, there are several alternative approaches to print newlines when working with single quotes.
Using PHP_EOL Constant
The PHP_EOL constant provides a cross−platform newline character that works in both CLI and web environments ?
<?php
$text1 = 'First line';
$text2 = 'Second line';
echo $text1 . PHP_EOL . $text2;
?>
First line Second line
Using Double Quotes for Newline
You can combine single quotes with double−quoted newline characters ?
<?php
$var1 = 'Hello';
$var2 = "<br>";
$var3 = 'World';
echo $var1 . $var2 . $var3;
?>
Hello World
Using chr() Function
The chr(10) function returns the newline character (ASCII 10) ?
<?php
$message = 'Line 1' . chr(10) . 'Line 2';
echo $message;
?>
Line 1 Line 2
Environment-Specific Approach
For applications that run in both CLI and web environments, you can detect the interface and use appropriate newline characters ?
<?php
function getNewline() {
if (PHP_SAPI === 'cli') {
return PHP_EOL;
} else {
return '<br>';
}
}
echo 'First line' . getNewline() . 'Second line';
?>
Comparison
| Method | Use Case | Cross-Platform |
|---|---|---|
PHP_EOL |
General purpose | Yes |
" |
Simple newline | Unix/Linux |
chr(10) |
ASCII approach | Unix/Linux |
Conclusion
When working with single quotes in PHP, use PHP_EOL for cross−platform compatibility or concatenate with double−quoted " characters. The
"PHP_EOL constant is the most reliable approach for newlines in PHP applications.
