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.