106

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
vespino
  • 1,714
  • 3
  • 15
  • 28

2 Answers2

156

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']);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
ArSeN
  • 5,133
  • 3
  • 19
  • 26
  • Seems logical, slapping myself thinking I could of thought of this myself. Blaming last night, it was late :) Will be a hell of a job to change all these occurrences, but beats moving to another system. I will test it with one occurrence first. Thanks. – vespino Dec 14 '19 at 20:04
  • 3
    i have this error i dont understand your explanation – Kipruto Jul 24 '20 at 21:37
  • 1
    @kipruto If you do not find an answer satisfactory you can always ask a new question. However please note that even this was marked as a duplicate since this is a fairly common question, so reading other answers might be a good first step. – ArSeN Jul 26 '20 at 07:38
  • @kipruto changing to php7.2 fixes this error – 00-BBB Mar 18 '21 at 13:49
  • 6
    I would strongly advise against using an old PHP version that is [not supported anymore](https://www.php.net/supported-versions.php) like it is the case for 7.2. – ArSeN Mar 18 '21 at 14:11
  • No, not always. when doing a dump, I see the index DOES exist, yet PHP 7.1 keeps insisting that it does not. – Debbie Kurth Jun 13 '21 at 01:29
  • For me, i was running a project which built on symfony 2.7 and it was a cache issue, I removed the cache and the error was gone. – sh6210 Oct 12 '21 at 00:05
  • 3
    I don't think this is correct. If the index doesn't exist you get "Undefined index". This error means that the variable is null. – Barmar Nov 22 '21 at 22:33
  • @Barmar I was able to replicate the same error by doing this: `$arr = array(0 => array('name' => 'Ang'), 1 => array('name' => 'Bel')); print_r( $arr[3]['name']) ;` Since I'm accessing (`'name'`) from something that does not exists(`$arr[3]`) , the error is Trying to access array offset on value of type null... so this answer is correct. – Gellie Ann Mar 25 '22 at 04:09
  • @Barmar is correct as you can easily test: https://3v4l.org/Yoh6Q / https://3v4l.org/lu3fj – Tgr Sep 08 '22 at 20:17
  • @Tgr there is "edit" button under the answer. – Your Common Sense May 23 '23 at 09:43
1

This error means that you are trying to use a null (or a non-existent value) as array. Which definitely means that logic of your program is broken.

First of all you must understand that every error message PHP generates is meant to help you, and to make your code cleaner and less error-prone. When your code contains a bug, your best bet is to fix it, not to brush it off. Sadly, the accepted answer only elaborates on the latter. But you should really consider doing the former.

Every error message helps you to find a bug in the code. It means that errors shouldn't be intentional or "habitual". This way you won't have to silence them, and every error would mean that your code indeed encountered a bug.

Like in your case. It just makes not sense to access a null or a non-existent variable as s though it's array. You can only use array offset on arrays, special type of objects and (using only numeric indices) on strings. But if you get a null value where array is expected, it means that the data flow in your program is broken. And you need to fix it.

Like in your case. Definitely, $cOTLdata contains null while your code expects it to be an array. Therefore, you need to fix the code that assigns value to $cOTLdata.

So, as a rule, just make sure that every function that should return an array, returns an array, or any variable that should contain an array, contains an array. And you won't see this error message again. Unless, due to some mistake, your code will return a non-array value unexpectedly. And this error message will help you to pinpoint this problem.

When things are not under your control, like, you need to get an array from an outside variable, do a validation first. For example, in case you are expecting an array from a form, that is obligatory, validate it and return an error, like

if (!$isset($_POST['options']) || !is_array($_POST['options'])) {
   // inform the user ad stop execution
} else {
    $options = $_POST['options'];
}
// now you can safely use count() on $options

In case the array is optional, you may initialize it as empty array:

if (!$isset($_POST['options'])) {
    $options = [];
} elseif (!is_array($_POST['options'])
   // inform the user ad stop execution
} else {
    $options = $_POST['options'];
}
// now you can safely use count() on $options

And only as a last resort you may silence this error, using is_null() or isset()

But you shouldn't just mindlessly use it as a generic solution. Using isset() won't fix the problem. It will just sweep it under the rug, effectively action as error suppression operator, so when some your function will start returning incorrect value, you will never get an helpful error message that explains, why your program suddenly stopped working.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345