Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eugenefvdm's avatar

Please assist with isset routine conversion to shorter / PHP 8 syntax

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;
    }
0 likes
4 replies
Snapey's avatar

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?

MichalOravec's avatar
Level 75
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
    };
}
1 like
eugenefvdm's avatar

@MichalOravec thank you so much. I didn't even know about match which I see is new with PHP 8.0. I learnt a lot by looking at how you solved the problem!

Please or to participate in this conversation.