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.
What are your thoughts on "Improving readability using array_filter"?