Php echo with new lines

echo

Outputs one or more expressions, with no additional newlines or spaces.

echo is not a function but a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas, and not delimited by parentheses. Unlike some other language constructs, echo does not have any return value, so it cannot be used in the context of an expression.

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This syntax is available even with the short_open_tag configuration setting disabled.

The major differences to print are that echo accepts multiple arguments and doesn’t have a return value.

Parameters

One or more string expressions to output, separated by commas. Non-string values will be coerced to strings, even when the strict_types directive is enabled.

Return Values

Examples

Example #1 echo examples

echo «echo does not require parentheses.» ;

// Strings can either be passed individually as multiple arguments or
// concatenated together and passed as a single argument
echo ‘This ‘ , ‘string ‘ , ‘was ‘ , ‘made ‘ , ‘with multiple parameters.’ , «\n» ;
echo ‘This ‘ . ‘string ‘ . ‘was ‘ . ‘made ‘ . ‘with concatenation.’ . «\n» ;

// No newline or space is added; the below outputs «helloworld» all on one line
echo «hello» ;
echo «world» ;

// Same as above
echo «hello» , «world» ;

echo «This string spans
multiple lines. The newlines will be
output as well» ;

echo «This string spans\nmultiple lines. The newlines will be\noutput as well.» ;

// The argument can be any expression which produces a string
$foo = «example» ;
echo «foo is $foo » ; // foo is example

$fruits = [ «lemon» , «orange» , «banana» ];
echo implode ( » and » , $fruits ); // lemon and orange and banana

// Non-string expressions are coerced to string, even if declare(strict_types=1) is used
echo 6 * 7 ; // 42

// Because echo does not behave as an expression, the following code is invalid.
( $some_var ) ? echo ‘true’ : echo ‘false’ ;

// However, the following examples will work:
( $some_var ) ? print ‘true’ : print ‘false’ ; // print is also a construct, but
// it is a valid expression, returning 1,
// so it may be used in this context.

echo $some_var ? ‘true’ : ‘false’ ; // evaluating the expression first and passing it to echo
?>

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.

Note: Using with parentheses

Surrounding a single argument to echo with parentheses will not raise a syntax error, and produces syntax which looks like a normal function call. However, this can be misleading, because the parentheses are actually part of the expression being output, not part of the echo syntax itself.

echo( «hello» );
// also outputs «hello», because («hello») is a valid expression

echo( 1 + 2 ) * 3 ;
// outputs «9»; the parentheses cause 1+2 to be evaluated first, then 3*3
// the echo statement sees the whole expression as one argument

echo «hello» , » world» ;
// outputs «hello world»

echo( «hello» ), ( » world» );
// outputs «hello world»; the parentheses are part of each expression

echo( «hello» , » world» );
// Throws a Parse Error because («hello», » world») is not a valid expression
?>

Passing multiple arguments to echo can avoid complications arising from the precedence of the concatenation operator in PHP. For instance, the concatenation operator has higher precedence than the ternary operator, and prior to PHP 8.0.0 had the same precedence as addition and subtraction:

// Below, the expression ‘Hello ‘ . isset($name) is evaluated first,
// and is always true, so the argument to echo is always $name
echo ‘Hello ‘ . isset( $name ) ? $name : ‘John Doe’ . ‘!’ ;

// The intended behaviour requires additional parentheses
echo ‘Hello ‘ . (isset( $name ) ? $name : ‘John Doe’ ) . ‘!’ ;

// In PHP prior to 8.0.0, the below outputs «2», rather than «Sum: 3»
echo ‘Sum: ‘ . 1 + 2 ;

// Again, adding parentheses ensures the intended order of evaluation
echo ‘Sum: ‘ . ( 1 + 2 );

If multiple arguments are passed in, then parentheses will not be required to enforce precedence, because each expression is separate:

echo «Hello » , isset( $name ) ? $name : «John Doe» , «!» ;

Источник

How to Add a New Line in PHP (Line Breaks, Explained)

We explore some of the best ways to add a line break to a string in your PHP code.

Suppose you’re building an app using PHP. (Which, since you’re reading this, you probably are.)

You need to include a long string of text that needs to be broken by line breaks so it’s easy for your users to read. And so, you found yourself wondering…

What’s the best way to accomplish this?

To add new lines to a string in PHP, echo the string using the nl2br() function, adding \n wherever you want the lines inserted. The function will return a string with a
element inserted before every \n character.

It is as simple as that. If you haven’t used the nl2br() function (the name stands for “newline to break”), it takes a while to learn the ropes. In the rest of this post, I’m going to show you exactly how to use it.

How the nl2br() Function Works

PHP, like most other programming languages, has support for the “end of line” or “newline” character, which tells the interpreter to insert a newline in the output of your code.

This is done by using the nl2br() function. The function parses the string, looks for \n characters, then returns a new string with \n converted into
elements. In turn, the user’s browser converts the
elements into line breaks as it renders the DOM.

Newline With /n

In the simplest implementation imaginable, your use of the nl2br() function would look like this:

php echo nl2br("Insert a new line \nbefore here"); ?>

The above function will return the following output:

Insert a new line br />before here

It’s important to note the PHP also allows you to use \r , \r\n , and \n\r instead of \n for end of line characters. You can use these interchangeably, although—to make your code consistent and easy to debug—it’s a good idea to select one and stick to it.

Newline With \r

php echo nl2br("Insert a new line \rbefore here"); ?>

Newline With \n\r

php echo nl2br("Insert a new line \n\rbefore here"); ?>

Newline With \r\n

Or, last but not least, this:

php echo nl2br("Insert a new line \r\nbefore here"); ?>

Which Line Break Character to Use?

Decisions, decisions… Which newline character should you use?

The \r is for “carriage return” and originates from the days when the paper carriage on typewriters and mechanical printers had to be slid back into position and rotated upward to start a new line. The \n stands for “newline” for a new line triggered by the “typist.”

Operating systems and programming languages in the early days of computing adopted both carriage return ( \r ), newline ( \n ), and the carriage return followed by newline ( \r\n ) as it was sequenced on typewriters.

Of course, each picked up a different one:

  • The ASCII standard is \r\n , and this is what MS DOS used;
  • UNIX used \n instead, and it got picked up by many languages;
  • Before OS X, Macs used an \r . Post OS X, Macs used the UNIX \n .

Nowadays, which one to use comes down to your personal preference. Carriage return keeps the mouse cursor on the existing line, whereas newline moves it to the new line.

With all that said, most of the programmers I know use \n for the languages that support it. Also, in terms of length, \n and \r require half the characters as \r\n and \n\r , so I see no reason to use the latter.

The Alternative: PHP_EOL

In PHP, there’s a reserved word called PHP_EOL . It’s basically a predefined constant that the PHP documentation describes as “The correct ‘End of Line’ symbol for this platform.”

PHP_EOL , as you will see in the code snippet below, eliminates the need to use the nl2br() function:

php $text = "Insert a new line" . PHP_EOL . "before here"; echo $text; ?>

According to a user in this Stackoverflow thread, the purpose of PHP_EOL is to automatically choose the correct line break character so that your code is always compatible, no matter the operating system it’s run on.

In Conclusion

That’s that. Though there are more ways to approach this, the nl2br() function and the PHP_EOL predefined constant should do the job, respectively, for HTML and non-HTML apps.

Let me know in the comments if you can think of any sleeker approaches, or if you’ve come across any limitations or edge cases of the above that are worth sharing with the rest of this post’s readers.

2 comments

There is no nlbr() function in PHP. All your code snippets are wrong. The function is called nl2br().

Leave a comment Cancel reply

  • How to Wait for an Element to Exist in JavaScript July 13, 2023
  • How to Check If a Function Exists in JavaScript July 13, 2023
  • How to Remove Numbers From a String With RegEx July 13, 2023
  • How to Check If a String Is a Number in JavaScript July 13, 2023
  • How to Insert a Variable Into a String in PHP July 12, 2023

We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.

Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.

These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Читайте также:  Таблица в центре окна
Оцените статью