When should escaping be used in PHP code?

Escaping should be used in PHP code whenever user input is being displayed on a webpage to prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks. By escaping user input, special characters are converted into their HTML entity equivalents, ensuring that the input is displayed as plain text and not executed as code.

$user_input = "<script>alert('XSS attack!');</script>";
echo htmlentities($user_input);