skip to Main Content

I inherited a WordPress website built on an older version of php. I’m getting this error on php 7.4
Trying to access array offset on value of type null in functions.php on line 846 - 849 The four lines are part of some custom code the developer created that I don’t entirely understand, so I’m not sure how to fix it. Research leads me to believe it’s not checking if the array is empty. I’ve tried to do that but nothing works. Hoping someone can catch the problem.

Line 846 starts at 'Icon1' and line 849 at 'Icon4'

function add_icons( $post_id ) {
$MyArray_field = get_field( 'custom_icons', $post_id );
    $MyArray       = array(
        'Icon 1' => $MyArray_field['field_name_1'] ? '<span class="field1" title="Icon 1">1</span>' : '',
        'Icon 2' => $MyArray_field['field_name_2'] ? '<span class="field2" title="Icon 2">2/span>' : '',
        'Icon 3' => $MyArray_field['field_name_3'] ? '<span class="field3" title="Icon 3">3</span>' : '',
        'Icon 4' => $MyArray_field['field_name_4'] ? '<span class="field4" title="Icon 4">4</span>' : '',
    );
    $MyArray       = array_filter( $MyArray );

    return implode( ' ', $MyArray );
}

2

Answers


  1. Chosen as BEST ANSWER

    After consulting with a few more developers, it was pointed out to me that it was not an error, but a "Notice:" I was getting on that function so I decided to hide it for now. Yes, it's a hack, but I can't afford to hire someone to fix small problems. If I start getting more problems from the php update, I will come up with a better solution.


  2. Check for key exist or not using isset()

    try this

    function add_icons( $post_id ) {
    $MyArray_field = get_field( 'custom_icons', $post_id );
        $MyArray       = array(
            'Icon 1' => isset($MyArray_field['field_name_1']) ? '<span class="field1" title="Icon 1">1</span>' : '',
            'Icon 2' => isset($MyArray_field['field_name_2']) ? '<span class="field2" title="Icon 2">2/span>' : '',
            'Icon 3' => isset($MyArray_field['field_name_3']) ? '<span class="field3" title="Icon 3">3</span>' : '',
            'Icon 4' => isset($MyArray_field['field_name_4']) ? '<span class="field4" title="Icon 4">4</span>' : '',
        );
        $MyArray       = array_filter( $MyArray );
    
        return implode( ' ', $MyArray );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search