Search code examples
phpphp-7.4

Message: Trying to access array offset on value of type null


I'm getting this error on multiple occasion in a script (invoiceplane) I have been using for a few years now but which hasn't been maintained unfortunately by its creators:

Message: Trying to access array offset on value of type null

My server has been upgrade to PHP 7.4 and I'm looking for a way to fix the issues and maintain the script myself since I'm very happy with it.

This is what's on the line that gives the error:

$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);

$cOTLdata is passed to the function:

public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
    $len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
    $nLeft = 0;
    $nRight = 0;
    //etc

It's included in mpdf btw, but simply overwriting the files from the github repository did not fix the errors.


Solution

  • This happens because $cOTLdata is null. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

    To check whether $cOTLdata is null use is_null():

    is_null($cOTLdata)
    

    Which means the line should look something like this:

    $len = is_null($cOTLdata) ? 0 : count($cOTLdata['char_data']);
    

    However, in case both $cOTLdata and $cOTLdata['char_data'] could not exist, you can use isset() for both at once:

    $len = !isset($cOTLdata['char_data']) ? 0 : count($cOTLdata['char_data']);