How can PHP developers ensure that line breaks are properly interpreted in textareas when using variables with line breaks?

When using variables with line breaks in textareas in PHP, developers can ensure that the line breaks are properly interpreted by using the nl2br() function. This function converts newlines in a string to HTML line breaks. By applying nl2br() to the variable before outputting it in the textarea, the line breaks will be displayed correctly.

<?php
// Example variable with line breaks
$text = "This is a line with\na line break.";

// Apply nl2br() function to convert newlines to HTML line breaks
$text_with_line_breaks = nl2br($text);

// Output the variable in a textarea
echo "<textarea>$text_with_line_breaks</textarea>";
?>