Image for post
Image for post

Laravel: Accessing Arrays & Objects

From my experience of working with PHP, it can be really painful if you work with objects and arrays. One of the many errors in PHP is the “Undefined Index” notice. I assume that every developer encountered that already. There are several ways of preventing this in PHP, and besides the general and probably already known ways, I want to show you how laravel can support you there, by using the build-in array and object helpers.

PHP has a variety of checks that can be done before working with arrays and objects. Just to mention a few we go with: isset(), array_key_exists(), property_exists() or even worse empty() (see. Good To Know: The empty() Function). But what do these functions all have in common? They complicate your code by adding extra if conditions to it.

Valid and maybe even performant, but unnecessary complex and ugly.

I know what you want to say. There is also the Null Coalesce Operator operator or the short form of writing an IF Statement. But this also ads unnecessary complexity.

This is where one of Laravel’s many advantages gets really handy, the array and object helpers.

Laravel, on the other hand, has functions and facades helping you to write more readable, shorter and less complex code.

For example, we want to access the array key of my previous code. In Laravel, it would be only one line of code.

echo Arr::get($data, 'likes');

And for the nonexisting case, we can just simply pass a third parameter that returns the default value if the key does not exist.

echo Arr::get($data, 'not', '1');

Pretty cool, huh? And it gets even better. Imagine that your array structure is even deeper and soon the code ends up in something like the following (if you secure array access).

Laravel instead has the dot notation and this makes it much easier, efficient and more readable to get the data.

echo Arr::get($data, 'more.complex.0');

Now the only thing missing is how we can access the properties of an object.

Also here Laravel has a pretty handy helper function allowing us to work as easy as with arrays, even dot notation is possible!

Laravel has powerful helpers and this article barely scratched on the surface of array and object helpers. I can only recommend switching immediately to this way of handling data since it was such a quality improvement to me by doing so.

I personally don’t like the empty() function and I recommend every developer not to use it, due to the fact that it is an explicit silencer and can lead to dead code as you can see in the following example.

Execute the code and see what happens?

Head of Backbone Panel Development / Cloud-Services Cloud-Panel at ABOUT YOU GmbH Employed since 01.06.2015

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store