What is the purpose of the nl2br function in PHP and how does it affect line breaks in text?

The nl2br function in PHP is used to convert newline characters (\n) in a string to HTML line breaks (<br>). This is useful when displaying text from a database or a form input where line breaks are represented by newline characters. By using nl2br, the text will be properly formatted with line breaks in an HTML context.

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