Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

php-7.4

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.

like image 966
vespino Avatar asked Dec 14 '19 16:12

vespino


People also ask

What does it mean trying to access array offset on value of type null?

It means that you tried to access an array using a NULL as an index. You can't do that. It has to be a positive number 0 (zero) and above but not higher than the size of the array. Remember that arrays start at 0 (zero) not 1.

What is array offset in PHP?

It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.


1 Answers

This happens because $cOTLdata is not null but the index 'char_data' does not exist. 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 the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

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

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

like image 168
ArSeN Avatar answered Oct 03 '22 19:10

ArSeN