Cannot Use String Offset as Array
The code tries to access a string using array syntax, treating it as an array.
Explanation
This error occurs when you try to use array access syntax on a string value. For example, \$string['key'] or \$string[5] on a string variable. While strings can be accessed by numeric index (returning a character), using string keys on a string is invalid. This commonly happens when a variable expected to be an array is actually a string, often due to incorrect data types from APIs or database results.
Common Causes
- Variable is string instead of array
- JSON not decoded to array
- API response type mismatch
- Database column contains string
- Function returns different type than expected
Solution
Check the variable type before using array access. Use is_array() to verify the variable is an array. Use json_decode() to convert JSON strings to arrays (with the second parameter as true). Add type checks or type casting where needed. In Laravel, use Arr::wrap() to ensure you always have an array. Debug with dd() or var_dump() to see what the variable actually contains.
Code Example
// Variable is a string, not an array
$config = '{"host": "localhost", "port": 3306}'; // JSON string
$config['host']; // Error: cannot use string offset as array
// Fix: decode JSON to array
$config = json_decode('{"host": "localhost", "port": 3306}', true);
$config['host']; // Works
// Using Arr::wrap in Laravel
use Illuminate\Support\Arr;
$value = 'single value';
$arr = Arr::wrap($value); // ['single value']
Error Information
Language
php
Difficulty
Beginner
Views
14
Related Errors
Database
Unknown Column
The SQL query references a column that doesn't exist in the specified table.
PHP
Maximum Execution Time Exceeded
A script ran longer than the allowed maximum execution time limit.
404
Laravel
ModelNotFoundException (404)
Thrown when a requested model instance cannot be found in the database.
Database
Column Count Doesn't Match
The number of values in an INSERT statement doesn't match the number of columns.