Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

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.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month 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.

Comments

What are your thoughts on "Improving readability using array_filter"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.