122

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.

3
  • Change it to $len = count($cOTLdata['char_data'] ?? []); Commented Aug 27, 2020 at 1:16
  • I had this same crash; I fixed it by moving to mpdf8 (I think on the version number) Commented Jun 4, 2021 at 11:22
  • Unfortunately newer PHP versions are more strict on such declarations Commented May 30, 2023 at 14:55

8 Answers 8

167

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']);
Sign up to request clarification or add additional context in comments.

12 Comments

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.
i have this error i dont understand your explanation
@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.
I would strongly advise against using an old PHP version that is not supported anymore like it is the case for 7.2.
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.
|
3

This error means that you are trying to use null as array. What your code trying to do here is like null['char_data'], which obviously makes no sense.

There could be two reasons for this error to appear:

  1. Some function may return either a meaningful array or null.
  2. A bug in your code.

When null value is expected

There are cases when null is a legitimate value. For example, a function may return either a meaningful array or null, as it happens with PHP mysqli API. In this case this return value has to be tested first, like this:

    $row = $stmt->fetch_assoc();
    if ($row !== null) { // the record was found and can be worked with
        echo $row['name'];
    }

Another case is when you are dealing with outside variable or any other situation when things are not under your control. In this case, you have to validate that input data first.

For example, in case you are expecting an array from a form, and this array is obligatory, validate it and return an error, like

if (!isset($_POST['options']) || !is_array($_POST['options'])) {
   // inform the user and 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

In case it's a bug in your code

You have to fix it.

You must understand that using isset() won't fix the problem. It will just sweep it under the rug, effectively acting as the error suppression operator, so when some your function will start returning incorrect value, you will never get a helpful error message that would have explained, why your program suddenly stopped working.

6 Comments

Having a "null", is not necessarily a error. You could be using boolean thinking of a 0 vs 1 and more as a flag. thus not a logic error. This is a common method in most all other languages. Just a thought.
@DebbieKurth not sure I follow. What does 0, 1 or boolean to do with arrays?
What appears to be happening, is the PHP computation is having problems with the embedded array and using the output. It is a nested computation issue that is Normal in other languages. The comment of "it is a logic error of code" is not really true. It the PHP software having trouble with nested references. thus a solution of $key = isset($value['offset']) ? $value['offset']: 0; Goes around the issue.
@DebbieKurth no, "PHP software" DOES NOT have any trouble with "nested references" (and this error has nothing to do with "nested references" at all). If accessing $value['offset'] causes this error, it means YOUR code is having trouble, not PHP. This error means that $value is NULL but for some unknown reason your code is trying to treat this null as array, which would make no sense an any language. So instead of fixing this error you are just silencing it out. Besides, to silence this error you must do isset($value), not isset($value['offset']) as in your example.
Well it fails unless you pull it out of a nested, giving the error of "Warning - Trying to access array offset on value of type null". so what can I say. I have had to go through all my plugin software and correct, so the error is removed. Pulling the nested computation out. All you do is pull the statement out and place into another variable. The reference the variable in the original line, usually a nested HTML value when using echoing technique. Then it works.
|
1

The given warning:

Warning - Trying to access array offset on value of type null - PHP 7.4.0 #7776

results form this snippet $key = $key[1]; and can be solved by using this instead:

$key = isset($key[1]) ? $key[1] : null;

Comments

0

Quick Fix for those that are not looking for the in depth detail, which I appreciated. I was using an outdated setup instructions for XenForo

if ($_POST['t'] == 0) {
    /* get by id */
    $finder = \XF::finder('XF:User');
    $user = $finder->where('user_id', $_POST['v'])->fetchOne();
} else {
    /* get by name */
    $finder = \XF::finder('XF:User');
    $user = $finder->where('username', $_POST['v'])->fetchOne();
}
$columns = array("user_id", "username", "last_username");
for ($i = 0; $i < sizeof($columns); $i++) {
    $column = $columns[$i];
    $columns[$i] = array($column, $user[$column]);
}

so just add the php !isset || !is_array

if (!isset($_POST['t']) || !is_array($_POST['t'])) {
    /* get by id */
    $finder = \XF::finder('XF:User');
    $user = $finder->where('user_id', $_POST['v'])->fetchOne();
} else {
    /* get by name */
    $finder = \XF::finder('XF:User');
    $user = $finder->where('username', $_POST['v'])->fetchOne();
}
$columns = array("user_id", "username", "last_username");
for ($i = 0; $i < sizeof($columns); $i++) {
    $column = $columns[$i];
    $columns[$i] = array($column, $user[$column]);
}

Comments

0

Before accessing any element within the array, ensure the entire array itself is not null you can use if statement and isset() methood check like below

if(!isset($cOTLdata)){
//Handle the case where array is null
  return;
}
$list=$cOTLdata['char_data'];
}

Comments

0

if you are facing this issue in mpdf then

  1. go to Mpdf.php
  2. search for this line: $e = $this->otl->applyOTL($e, $this->CurrentFont['useOTL']);
  3. replace it with :$e = preg_replace("/[\xe2\x80\x8c\xe2\x80\x8d\xe2\x80\x8e\xe2\x80\x8f]/u", '', $e); $e = preg_replace("/[\xef\xbb\xbf]/u", '', $e);

1 Comment

If possible, please use code blocks to make the answer more readable :)
0

I am new to PHP but this fixed my issue.

  $user_type_res = $connection->query(query: "SELECT `user_type` from `users` WHERE email='$email'");
      $user_type = $user_type_res->fetch_assoc()['user_type'];

So the idea is to query the column on the table first then fetch the association of that column to get the data

Comments

-1
<?php
require './connect/config.php'; // Database connection
session_start();

if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo "<h2 class='text-center text-danger'>Category not found!</h2>";
    exit;
}

$category_id = intval($_GET['id']);

// Fetch Category Details
$categoryQuery = $conn->prepare("SELECT * FROM categories WHERE id = ?");
$categoryQuery->bind_param("i", $category_id);
$categoryQuery->execute();
$categoryResult = $categoryQuery->get_result();
$category = $categoryResult->fetch_assoc();

if (!$category) {
    echo "<h2 class='text-center text-danger'>Invalid category!</h2>";
    exit;
}

// Fetch Products under this Category
$productQuery = $conn->prepare("SELECT * FROM products WHERE category_id = ?");
$productQuery->bind_param("i", $category_id);
$productQuery->execute();
$productResult = $productQuery->get_result();
?>

1 Comment

This does not seem relevant to the question. The complete lack of any explanation as to how this code is supposed to solve the problem does not help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.