How can I fix 'Trying to access array offset on value of type bool' error in my PHP code?

331 views Asked by At
Notice: Trying to access array offset on value of type bool in

I got this for each loop:

foreach($ids as $id){
    if (stripos($field['name'], 'label_') !== FALSE) {
        echo '';
    }
    else{
        $val = get_field_object($field['name'], $id);
        echo '<td>'.generate_view($field['name'], $val['value']).'</td>';
    }
}

The error is saying this line is incorrect:

echo '<td>'.generate_view($field['name'], $val['value']).'</td>';

This error just came for the first time and I realy need to fix it but I don't know what it is saying and how to solve. Anyone can help me out?

I searched and found other posts regarding this issue on Stackoverflow but can't figure out to translate the answers in order to fix my problem:(

2

There are 2 answers

0
Heidar Ammarloo On

check if $val is null echo '';

foreach($ids as $id){
    $val = get_field_object($field['name'], $id);
    if (stripos($field['name'], 'label_') !== FALSE OR !$val) {
        echo '';
    } else{
        echo '<td>'.generate_view($field['name'], $val['value']).'</td>';
    }
}
0
Collei Inc. On

Adapted with the due, readable checks. Feel free to shorten or modify it.

foreach($ids as $id){
    $view_content = '';

    // Captures $val
    $val = get_field_object($field['name'], $id);

    // Checks if $val is an array or not
    $val_is_array = (array)$val === $val;

    // Checks for label validity
    $valid = stripos($field['name'], 'label_') !== FALSE;

    // Only fills $view_content when both conditions are met
    if ($valid && $val_is_array) {
        $view_content = '<td>'.generate_view($field['name'], $val['value']).'</td>';
    }

    // Outputs it
    echo $view_content;
}