What is the function nl2br() used for in PHP and how can it be implemented to preserve line breaks?

The nl2br() function in PHP is used to convert newline characters (\n) into HTML line breaks (<br>). This function is commonly used when displaying text that contains line breaks in an HTML document to ensure that the line breaks are preserved and displayed correctly.

$text = &quot;Hello\nWorld&quot;;
echo nl2br($text);