Uncaught TypeError: Cannot access offset of type string on string in PHP 8
Upgrading from PHP 7 to PHP 8 introduces a strict set of rules regarding array data types that often break legacy codebases overnight. A common casualty of this transition is the Uncaught TypeError: Cannot access offset of type string on string error. This specific failure usually stems from how multi-dimensional arrays are accessed, particularly when an intermediate key in a nested structure turns out to be a string instead of an array.
The error originates from a line accessing $course_data['steps']['h']["sfwd-lessons"]. In older PHP versions, this might have silently defaulted to an empty array or handled the mismatch more gracefully. However, PHP 8 enforces strict type checking on array offsets. If you attempt to access a key on a value that is not an array (e.g., $arr['key'] where $arr['key'] is a string), the runtime immediately halts execution with a TypeError.
In the provided code snippet, the logic attempts to extract lesson and quiz data from a post meta field ld_course_steps. The structure implies that $course_data['steps']['h'] contains an associative array of step types, such as "sfwd-lessons" and "sfwd-quiz". The crash occurs because one of these keysâlikely "sfwd-lessons" or "sfwd-quiz" within the 'h' indexâis not actually an array. Instead, it holds a scalar value (string, integer, or null).
When you run array_keys() on a non-array, or iterate over it using foreach, PHP 8 throws this specific exception before any logic can execute inside the loop. The initial check if(is_array(...)) is present, but if that condition evaluates to true for the outer wrapper and false for the inner target, the subsequent access fails.
Diagnosing the Data Structure
To resolve this, you must inspect the actual content of $course_data. The error suggests a mismatch between the expected schema (a nested array of steps) and the reality stored in the database or meta field. This often happens when data is imported from an incompatible version of the plugin or manually edited.
You can debug this by printing the raw structure before accessing the nested keys:
var_dump($course_data['steps']['h']);
// Output might look like:
// array(1) { ["sfwd-lessons"]=> string(2) "no" }
// instead of an array containing lesson data.
If 'sfwd-lessons' inside the 'h' index is a string rather than an array, any attempt to iterate over it will fail.
Implementing a Safe Access Pattern
The robust solution involves checking the type of every nested level before attempting to access its offsets. Instead of assuming that ['steps']['h'] leads directly to a collection of arrays, you must verify that each specific step key is an array.
Here is a corrected approach using strict type checks:
// Bail out if this is not an event item
if ('sfwd-courses' !== get_post_type($post_id)) {
return;
}
$course_data = get_post_meta($post_id, 'ld_course_steps', true);
if (empty($course_data)) {
return;
}
// Safely navigate the nested structure
$h_section = $course_data['steps']['h'] ?? [];
if (!is_array($h_section)) {
// Handle case where 'h' itself is not an array
return;
}
// Check specifically for the lessons key before accessing it
$lessons_key = 'sfwd-lessons';
if (!array_key_exists($lessons_key, $h_section) || !is_array($h_section[$lessons_key])) {
// Handle case where the specific lesson data is missing or malformed
return;
}
// Now safe to iterate
foreach ($h_section[$lessons_key] as $lesson) {
// Proceed with your logic here
if (is_array($lesson['sfwd-topic'])) {
foreach ($lesson['sfwd-topic'] as $topic) {
// Process topic
}
}
}
Why This Approach Works
By explicitly checking is_array() at every level of the hierarchy, you prevent PHP 8 from throwing a TypeError when it encounters a scalar value where an array is expected. The previous code assumed that if 'sfwd-courses' was valid, then all subsequent nested keys would also be arrays. This assumption breaks in PHP 8 when data inconsistencies exist.
Additionally, using array_key_exists() combined with is_array() provides a dual safety net. It ensures the key is present and that its value conforms to the expected array type before any iteration or offset access occurs.
This pattern is essential for maintaining backward compatibility during version upgrades. If your plugin relies on legacy data structures that might be incomplete, defensive coding prevents fatal errors from halting your application. Always validate the shape of your data against the schema you expect, especially when moving to stricter runtime environments like PHP 8.