How should the nl2br function be used effectively for formatting user-entered text within HTML output in a PHP application?

When displaying user-entered text within HTML output in a PHP application, the nl2br function can be used to convert newline characters (\n) to HTML line breaks (<br>). This ensures that the formatting of the text is preserved when displayed on the webpage. To use the nl2br function effectively, simply pass the user-entered text as an argument to the function before outputting it within the HTML code.

$userText = &quot;Hello\nWorld!&quot;;
$formattedText = nl2br($userText);
echo $formattedText;