Search code examples
phpwordpressfatal-errorphp-8

Uncaught TypeError: Cannot access offset of type string on string in


I got the error from the title after I update to PHP 8. The code is similar to the below and it said the error is on the line: if(is_array($course_data['steps']['h']["sfwd-lessons"])){

full code here:

// 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)) {
        $lessons = array_keys($course_data['steps']['h']["sfwd-lessons"]);
        $quizes = array_keys($course_data['steps']['h']["sfwd-quiz"]);
    }

$lesson_data = [];
    // Extract all steps of the courses
    if(is_array($course_data['steps']['h']["sfwd-lessons"])){
        foreach($course_data['steps']['h']["sfwd-lessons"] as $lesson){
            $lesson_data = array_merge($lesson_data,array_values(array_keys($lesson["sfwd-topic"])));
            $lesson_data = array_merge($lesson_data,array_values(array_keys($lesson["sfwd-quiz"])));
            foreach($lesson["sfwd-topic"] as $topic){
                $lesson_data = array_merge($lesson_data,array_values(array_keys($topic["sfwd-quiz"])));
            }
        }
    }

Solution

  • The problem here is that in PHP 8, this code error used to throw a 'warning' but now it's a fatal error. Don't worry, it's probably a pretty easy fix!

    The issue is that $course_data from your sample code is being returned as a string, and you're trying to use array offsets to on it. Try var_dump($course_data) right after the line that defines $course_data and see what type of data it's returning.

    Note that the third argument in get_post_meta() being set to true makes it return a 'single value', vs an array, so that's likely the issue. It's tough to say exactly what the fix is here without seeing what your data looks like, but the first step is definitely examining what get_post_meta() is returning for you.

    Hope this helps!