How to Fix Undefined Array Key Errors in Laravel/PHP

Published: 1 year ago - Updated: 1 year ago

4 minutes - 685 Words

article 'How to Fix Undefined Array Key Errors in Laravel/PHP' banner

Summary

I explain how to fix undefined array key errors in Laravel/PHP using optional chaining and null coalescing.

Introduction

In PHP, undefined array key errors in PHP occur when trying to access an element in an array using a key that doesn’t exist. This can be avoided by checking if a key exists in an array using either the isset() function or the array_key_exists() function.

In this artilce we will have a look at using array_key_exists() function.

Get Started

Let’s consider we have a model called Post::class and it has a generated field called banner which itself is an array with keys url and thumbnail.

The catch in this situation is that we might not have a thumbnail for every post and as a result we will get undefined array key error.

So let’s fix it.

Solution 1 - Using array_key_exits()

To do that as I mentioned above we will use array_key_exits() function. The function takes two argument.

  • key with type of string
  • array with type of array (This will become important later)

and it returns a boolean.


$post = new Post([
		'title' => 'My First Post',
		'body' => 'This is the body of my first post.',
		'author' => 'John Doe',
		'published_at' => '2023-08-23 10:00:00',
        'banner' => [
           'url' => '<http://localhost:8000/imgs/test.png>',
        ]
]);

$thumbnail = array_key_exists('thumbnail', $post->banner)
                            ? $post->banner['thumbnail']
                            : '<http://localhost:8000/imgs/default.png>';

In the above code snippet we first checked if the key exists then got its value from $post, if it didn’t have thumbnail then return a default link.

Other Scenarios

  1. If you don’t know the array($banner) would exists for sure in the post and we use the above solution we will get the bellow error.

property $banner does not exist,

To fix this we need use optional chaining while accessing banner property $post?->banner

$thumbnail = array_key_exists('thumbnail', $post?->banner)
           ? $post?->banner['thumbnail']
           : '<http://localhost:8000/imgs/default.png>';

  1. We haved solved the property $banner does not exist error But if that banner property is null and it is passed to array_key_exists() function, we would get this next error

`TYPE ERROR  array_key_exists(): Argument #2 ($array) must be of type array, null given in Music/1-Laravel/blog/vendor/psy/psysh/src/Exception/TypeErrorException.php on line 54.`

To fix it we need to use null coalising operator.

array_key_exists('thumbnail', $post?->banner ?? [])
           ? $post?->banner['thumbnail']
           : '<http://localhost:8000/imgs/default.png>';

Now if the banner key does not exists the second parameter of array_key_exists() would be an empty array and we wont get any errors.

Final Solution 1

namespace App\Models;

$post = new Post([
		'title' => 'My First Post',
		'body' => 'This is the body of my first post.',
		'author' => 'John Doe',
		'published_at' => '2023-08-23 10:00:00',
    'banner' => [
       'url' => '<http://localhost:8000/imgs/test.png>',
    ]
]);

$thumbnail = array_key_exists('thumbnail', $post?->banner ?? [])
           ? $post?->banner['thumbnail']
           : 'http://localhost:8000/imgs/default.png';

Solution 2 - Using Laravel Helpers data_get()

data_get() is global Laravel helper that retrieves a value from array using dot notation.

It also accepts a default value in case the key is not found in the array.

data_get($array,‘array.key’, ‘default’);

namespace App\Models;

$post = new Post([
		'title' => 'My First Post',
		'body' => 'This is the body of my first post.',
		'author' => 'John Doe',
		'published_at' => '2023-08-23 10:00:00',
    'banner' => [
       'url' => 'http://localhost:8000/imgs/test.png',
    ]
]);

$thumbnail = data_get($post->banner,'thumbnail','http://localhost:8000/imgs/default.png');

// http://localhost:8000/imgs/default.png

With data_get() even if banner is undefined we would get the default value that we passed to date_get() function.

Solution 3 - Using isset()

isset — Determine if a variable is declared and is different than **null and returns a boolean.

Description

isset(mixed $var, mixed ...$vars): bool

Here is how to handle undefined array key with isset

namespace App\Models;

$post = new Post([
		'title' => 'My First Post',
		'body' => 'This is the body of my first post.',
		'author' => 'John Doe',
		'published_at' => '2023-08-23 10:00:00',
    'banner' => [
       'url' => 'http://localhost:8000/imgs/test.png',
    ]
]);

$thumbnail = isset($post->banner['thumbnail'])
        ? $post?->banner['thumbnail']
        : 'http://localhost:8000/imgs/default.png';

Add Comment

Conversations (0)

Sign up for our newsletter

Stay up to date with the latest news and articles.