Skip to content

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

This error message indicates that you are trying to access an array offset (i.e., an element of an array) but the variable being accessed is null.

Here is an example of code that would trigger this error:

How to fix the "Message: Trying to access array offset on value of type null" error in PHP?

php
<?php

$arr = null;
echo $arr[0];

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

To fix this error, you will need to make sure that the value you are trying to access is not null. This might involve initializing the array or checking that the value is not null before trying to access it.

Fixing the "Message: Trying to access array offset on value of type null" error in PHP

php
<?php

$arr = [];  // Initialize the array

if (isset($arr[0])) {
  echo $arr[0];  // This will not trigger an error
} else {
  echo 'index does not exist';
}

Alternatively, you can use the null coalescing operator ?? for a more concise approach:

php
<?php
echo $arr[0] ?? 'index does not exist';

Note that isset() returns false if the key exists but the value is explicitly null. If you need to check for the presence of a key regardless of its value, use array_key_exists('0', $arr).

Dual-run preview — compare with live Symfony routes.