Skip to content
PHP Logo

What are the best practices for accessing array elements in PHP using dynamic indexes?

When accessing array elements in PHP using dynamic indexes, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or code injection. One way to do this is by using the `filter_input()` function to ensure the input is of the expected type. Additionally, it is recommended to check if the array key exists before trying to access it to avoid errors.

php
// Example of accessing array elements using dynamic indexes with input sanitization
$index = filter_input(INPUT_GET, 'index', FILTER_SANITIZE_NUMBER_INT);
$array = [1, 2, 3, 4, 5];

if (array_key_exists($index, $array)) {
    $element = $array[$index];
    echo $element;
} else {
    echo "Invalid index";
}