Home > Enterprise >  Error: Trying to access array offset on value of type null in my PHP code
Error: Trying to access array offset on value of type null in my PHP code

Time:02-15

I have limited knowledge of PHP. I am getting this error on this code in the forloop part.

Trying to access array offset on value of type null on line ...

I am seeing this in a local environment as well as online when I enabled debugging in a Wordpress project. I think is related to the nested forloop but I am not sure what the exact problem is.

The error is thrown on the line starting with the if condition after the try block. I have removed some of the code inside the if condition and replace them with ... What am I missing in the forloop or variable declaration code?

public function render_element_css( $code, $id ){
        
        global $kc;
        
        $css_code = '';
        $css_any_code = '';
        $css_desktop_code = '';
        $pro_maps = array( 
            'margin' => array('margin-top','margin-right','margin-bottom','margin-left'), 
            'padding' => array('padding-top','padding-right','padding-bottom','padding-left'), 
            'border-radius' => array('border-top-left-radius','border-top-right-radius','border-bottom-right-radius','border-bottom-left-radius')
        );
            
        try{    
            $screens = json_decode( str_replace( '`', '"', $code ), true );
            if (is_array( $screens['kc-css']))
            {
                kc_screen_sort ($screens['kc-css']);

                foreach ($screens['kc-css'] as $screen => $groups)
                {
                ...
                    
                }
            
            }
            
        }catch( Exception $e ){
             echo "\n\n/*Caught exception: ",  $e->getMessage(), "*/\n\n";
        };
        
        return kc_images_filter($css_any_code.$css_code);
        
    }

CodePudding user response:

Problem

This line:

$screens = json_decode( str_replace( '`', '"', $code ), true );

will make the json invalid before you're trying to decode it.

Imagine you have a string like this:

$json = '{"foo": "lorem `bar` ipsum"}';

If you run your current str_replace() on it before trying to decode the string, it will become:

$json = '{"foo": "lorem "bar" ipsum"}';

See the issues with the quotes? If you try to decode that using json_decode(), it will fail and return null, which means that $screens['kc-css'] will throw the error message you're getting.

Solution

You need to escape the double quote with a backslash: \" if you want to use a literal double quote inside a double quoted string.

Change it to:

$screens = json_decode( str_replace( '`', '\"', $code ), true );

and it should work.

Here's a demo

  • Related