In the context of PHP programming, what are some recommended methods for sanitizing and formatting array keys to avoid errors during array access operations?

When working with array keys in PHP, it is important to sanitize and format them properly to avoid errors during array access operations. One common issue is using user input directly as array keys without validation, which can lead to unexpected behavior or security vulnerabilities. To mitigate this, it is recommended to sanitize array keys by removing any special characters or spaces and ensuring they follow a specific format.

// Example of sanitizing and formatting array keys
$user_input = $_POST['key']; // Assuming this is user input

// Sanitize the user input by removing special characters and spaces
$sanitized_key = preg_replace('/[^a-zA-Z0-9_]/', '', $user_input);

// Format the key to ensure it follows a specific format (e.g., lowercase)
$formatted_key = strtolower($sanitized_key);

// Access the array using the sanitized and formatted key
$value = $my_array[$formatted_key];