DEV Community

pO0q 🦄
pO0q 🦄

Posted on

PHP: why use arrays?

If you come from other programming languages, you might be surprised by PHP arrays.

This very handy structure can store all kinds of elements, but it's not perfect.

PHP arrays in very short

At its core, an array is a map. It usually contains keys and values, and the values can be arrays, allowing you to build trees and other multidimensional structures if that makes sense:

$array = [
    "foo" => "bar",
    "bar" => "foo",
];

$array2 = [
    "foofoo" => "barbar",
    "barbar" => $array,
];

//etc
Enter fullscreen mode Exit fullscreen mode

The key is optional, and PHP will automatically increment numbers if you don't specify it.

If you read the documentation, it's quite easy to learn and use.

The dark side of PHP arrays

Arrays are ubiquitous in PHP. I mean, literally everywhere.

It's very convenient, as you have tons of built-in helpers and tools to make all kinds of sorting, filtering, and other common operations.

IMHO, that can be a valid reason to use such structure, especially if you want to handle lists of elements.

However, this is not magic at all. The big caveat is you can put pretty much everything in an array, sometimes making it harder to use safely and test.

It's not uncommon to write several lines of defensive code for type safety in nested arrays, not to mention the multiple isset() or empty() you will find in a typical PHP script.

It's not bad in itself, but some developers would prefer an object-oriented approach with a defined structure.

It gets worse if you start passing associative arrays to your functions, repeating the same tests, again and again.

function myfunc(array $params) {
    if (!isset($params['id'], $params['name']) {
        return 'Atchoum';
    }
}

// vs.
function myfunc(ParamObject $params) {}
Enter fullscreen mode Exit fullscreen mode

As you can see in the above example, you can only typehint a generic structure using the built-in arrays.

There are other ways

PHP has other structures you might not know yet:

  • generators: they provide quite the same feature (you can use them in a foreach loop) with less memory consumption, especially if you don't have to make complex operations (e.g., rewinding is not possible)
  • collections: you get stronger types, as your custom collection will only handle a specific subtype, and nothing more (e.g., Laravel collections)

Wrap this up

PHP arrays are very convenient, but be aware there is no magic recipe you can apply in every situation.

We saw a few alternatives that can improve several aspects of your code, including type safety and readability, while keeping a convenient syntax.

Top comments (0)