How can understanding PHP variable interpolation and escaping help prevent unexpected behavior when passing variables to functions like mail()?

When passing variables to functions like mail() in PHP, it is important to properly escape and interpolate the variables to prevent unexpected behavior such as injection attacks or formatting issues. This can be done by using functions like htmlentities() or addslashes() to escape user input and using double quotes to interpolate variables within strings.

// Example of properly escaping and interpolating variables when passing them to the mail() function
$to = "recipient@example.com";
$subject = "Message from " . htmlentities($name);
$message = "Hello, " . addslashes($message);

// Send the email using the escaped and interpolated variables
mail($to, $subject, $message);