I'm currently organising Full Stack Europe. It's a conference in Antwerp, Belgium for developers who want to learn across the stack. You can use this link get your ticket with a nice discount.

Improving readability using array_filter

Link –

In this post I'd like to share a quick tip on how you can improve the readability of your code with array_filter.

Today I was working on some code that looked something like this:

class Address
{
    ...

    public function toArray()
    {
        $address = [
            'name' => $this->name,
            'street' => $this->street,
            'location' => $this->location,
        ];

        if ($this->line2 != '') {
            $address['line2'] = $this->line2;
        }

        if ($this->busNumber != '') {
            $address['busNumber'] = $this->busNumber;
        }

        if ($this->country != '') {
            $address['country'] = $this->country;
        }


        return $address;
    }
}

Did you know that you can use array_filter to clean this up? I didn't, until today.

When that function is called without a second argument it will remove any element that contains a falsy value (so null, or an empty string) Here's the refactored, equivalent code:

class Address
{
    ...

    public function toArray()
    {
        return array_filter([
            'name' => $this->name,
            'street' => $this->street,
            'line2' => $this->line2,
            'busNumber' => $this->busNumber,
            'location' => $this->location,
            'country' => $this->country,
        ]);
    }
}

That's much better!

Just be careful when using this with numeric data that you want to keep in the array. 0 is considered as a falsy value too, so it'll be removed as well.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.