What is the significance of escaping characters when assigning values to variables in PHP?

When assigning values to variables in PHP, it is important to escape characters to prevent any potential security vulnerabilities or syntax errors. This is especially crucial when dealing with user input or data from external sources, as unescaped characters can be exploited to inject malicious code or disrupt the functionality of the script. By escaping characters, you ensure that the data is properly sanitized and can be safely used in your PHP code.

$userInput = "<script>alert('XSS attack!');</script>";
$escapedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $escapedInput;