Improving readability using array_filter


Great trick by Freek Van der Herten: instead of selectively adding fields onto an array after having verified them to not being falsy – resulting in lots of if blocks in the code – it’s actually a lot easier/readable to fill the array first and then successively filter out the empty values using array_filter.

When that function is called without a second argument it will remove any element that contains a falsy value.

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,

In case that – for example – $this->busNumber had a value of null in the example above, it would be omitted from the returned array.

Improving readability using array_filter

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.