How can one ensure proper variable substitution and array index interpretation in PHP when generating HTML output?

When generating HTML output in PHP, it's crucial to ensure proper variable substitution and array index interpretation to avoid errors or security vulnerabilities. To do this, always use proper escaping functions like htmlspecialchars() for variables to prevent XSS attacks. Additionally, when accessing array elements, make sure to check if the key exists before using it to avoid undefined index errors.

<?php
// Example of proper variable substitution and array index interpretation in PHP
$name = "<script>alert('XSS attack')</script>";
$users = array(
    1 => "Alice",
    2 => "Bob",
    3 => "Charlie"
);

// Proper variable substitution with htmlspecialchars()
echo "Hello, " . htmlspecialchars($name) . "<br>";

// Proper array index interpretation with isset()
$userId = 2;
if(isset($users[$userId])){
    echo "User with ID " . $userId . ": " . $users[$userId];
} else {
    echo "User with ID " . $userId . " not found";
}
?>