Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Improving readability using array_filter

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.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.
  • well, that was helpful 🙂

  • Markus Diehl

    Cool!

  • Roark McColgan

    Brilliant! Thank you

  • Raffaele Ricci

    Cool tip! If you don’t want to remove the values 0 from the array you can also pass a closure as second argument:

    array_filter( $array, function($value) { return $value !== null && $value !== ”; } );

    This way it will remove only null values or empty strings

    • Shandur

      You could do this much more easier just using this:

      $result = array_filter($array, ‘strlen’);

      All falsy values will be removed except zero 🙂

      You’re welcome:)

      • Raffaele Ricci

        Awesome! Definitely better 🙂

  • Pingback: Community News: Recent posts from PHP Quickfix (08.24.2016) – SourceCode()