close

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

To solve Message: Trying to access array offset on value of type null error you need to make sure whatever you are trying is not empty and variable must exist. You can use PHP inbuild function isset() and it will solve your error.

How Message: Trying to access array offset on value of type null Error Occurs?

I am trying to get some data and compare if null then shows 0 But I am facing the following error.

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

Here is the code That I am trying to access.

$total_usr = $allData['num_of_usr'] === null ? 0 : count($allData['num_of_usr']);

Solution 1: Use isset()

You just need to check that Your $allData of index num_of_usr exists or not. If your $allData of Index num_of_usr is not Exits then you will face this error. So All You need to do is Just Check whether the index exists or not you can use isset(). Just Like this.

isset($allData['num_of_usr'])

And Here is your final Code.

$total_usr = isset($allData['num_of_usr']) ? count($allData['num_of_usr']) : 0;

Now, Your error must be solved.

Summary

In short, you need to check if the variable or value exists or not and you can use isset() function for this now, your error must be resolved. Hope our article is helped you to solve this error.

Also, Read

15 thoughts on “[Solved] Message: Trying to access array offset on value of type null”

  1. Excellent worked perfect. Thanks for the contribution.

    previously:
    $userbd = $data[‘user’];
    $keybd = $data[‘key’];
    $user_idbd = $data[‘id’];

    After:
    $userbd = isset($data[‘user’]);
    $keybd = isset($data[‘key’]);
    $user_idbd = isset($data[‘id’]);

    Reply

Leave a Comment