Skip to content
PHP Logo

How can the error "Fatal error: Cannot use string offset as an array" be avoided when working with arrays in PHP?

The error "Fatal error: Cannot use string offset as an array" occurs when trying to access an element of a string as if it were an array. To avoid this error, you should ensure that you are working with arrays properly by checking the variable type before trying to access it as an array.

php
// Check if the variable is an array before accessing it
if (is_array($array) && isset($array['key'])) {
    // Access the element of the array
    $value = $array['key'];
    // Do something with $value
} else {
    // Handle the case where $array is not an array or the key does not exist
    echo "Error: Invalid array or key";
}