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.

JavaScript

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:

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement