Skip to content
Advertisement

Return a empty string if return is empty

So I have the following method that is sending back a response to my API, but I have one small problem that I’m trying to overcome.

public function transform($employee)
    {
        return [
            'birthday' => $employee['birthday']->format('Y-m-d'),
            'hire_date' => $employee['hire_date']->format('Y-m-d'),
        ];
    }

The 'birthday' and 'hire_date' return values back, but is there a way that I can define an empty string if there is no value?

Something along the lines like this: 'birthday' => $employee['birthday']->format('Y-m-d') :? '',

Advertisement

Answer

Yes, you can do it like this:

public function transform($employee)
    {
        return [
            'birthday' => !empty($employee['birthday']->format('Y-m-d')) ? $employee['birthday']->format('Y-m-d') : "",
            'hire_date' => !empty($employee['hire_date']->format('Y-m-d')) ? $employee['hire_date']->format('Y-m-d') : "",
        ];
    }

Additionally, if you’re running php 7 or greater, you can use the null coalescing operator like this:

public function transform($employee)
    {
        return [
            'birthday' => $employee['birthday']->format('Y-m-d') ?? ""
            'hire_date' => $employee['hire_date']->format('Y-m-d') ?? "",
        ];
    }

You can find more info in the php documentation

PS. as pointed out in the comments, the date format function will always return something, or a warning if $employee['birthday'] is null. So better to place the check on $employee['birthday'] like so:

            'birthday' => !empty($employee['birthday']) ?
                $employee['birthday']->format('Y-m-d') "",
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement