What are the best practices for handling arrays and accessing values in PHP, especially when dealing with user input like command line arguments?

When handling arrays in PHP, especially when dealing with user input like command line arguments, it is important to validate and sanitize the input to prevent vulnerabilities like injection attacks. To access values in an array safely, always check if the key exists before trying to access it to avoid potential errors. Additionally, consider using functions like filter_input() or filter_var() to sanitize user input.

// Example of handling command line arguments safely
$arguments = $_SERVER['argv'];

// Check if the argument exists before accessing it
if(isset($arguments[1])) {
    $userInput = filter_var($arguments[1], FILTER_SANITIZE_STRING);
    echo "User input: " . $userInput;
} else {
    echo "No user input provided.";
}