Level 122
with null coalesce it would still be the same number of lines
will it always be just the two variants it or could this list be extended?
Summer Sale! All accounts are 50% off this week.
Hi there,
I'm new to PHP 8 and I have the following code which I am almost 100% sure can be abbreviated to a much shorter syntax if using PHP 8. The key I think is PHP 8 has a ? syntax or something to avoid the isset. I've looked at some examples but my head just can't get around it.
Any tips?
private function getHostingType($domain) {
if (isset($domain->values->type)) { // TODO Does PHP 8.0 provide a shortcut for this?
if ($domain->values->type[0] == "Top-level server") {
return "Web Hosting";
}
if ($domain->values->type[0] == "Sub-server") {
return "Subdomain";
}
}
return null;
}
private function getHostingType($domain)
{
return [
'Top-level server' => 'Web Hosting',
'Sub-server' => 'Subdomain'
][$domain->values->type[0] ?? null] ?? null;
}
or
private function getHostingType($domain)
{
return match ($domain->values->type[0] ?? null) {
'Top-level server' => 'Web Hosting',
'Sub-server' => 'Subdomain',
default => null
};
}
Please or to participate in this conversation.