'PHP message: PHP Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` [duplicate]

I'm having an issue with the piece of code below. I believe I just need to add parentheses but I'm not sure where. Thanks

$host = isset( $s['HTTP_X_FORWARDED_HOST'] ) ? $s['HTTP_X_FORWARDED_HOST'] : isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];

php


Solution 1:[1]

although it is often nice to write logic in shorthand, I would personally never sacrifice readability over brevity.

private function getFoo(array $s): string {
    if (isset($s['HTTP_X_FORWARDED_HOST'])) {
        return $s['HTTP_X_FORWARDED_HOST'];
    }

    if (isset($s['HTTP_HOST'])) {
        return $s['HTTP_HOST'];
    }

    return $s['SERVER_NAME'];
}

can also be slightly shorter by doing using the null coalescing operator

private function getFoo(array $s): string {
    if (isset($s['HTTP_X_FORWARDED_HOST'])) {
        return $s['HTTP_X_FORWARDED_HOST'];
    }

    return $s['HTTP_HOST'] ?? $s['SERVER_NAME'];
}

if you do insist on doing the shorthand version, tnavidi's answer is the way to go

Solution 2:[2]

I suppose you want it from left to right, so it should be

$host = isset( $s['HTTP_X_FORWARDED_HOST'] ) ? $s['HTTP_X_FORWARDED_HOST'] : (isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : $s['SERVER_NAME']);

i.e, the latter a ? b : (c ? d : e)-part of the error message

Solution 3:[3]

That way to nest ternary operators was deprecated because it's so unreadable that it was often used incorrectly.

Figuring out from the key names, the intention of your code is to set the variable to the first available value, left to right. Almost any alternative is easier to maintain, but if you're prone to one-liners you can try this:

$host = $s['HTTP_X_FORWARDED_HOST'] ?? $s['HTTP_HOST'] ?? $s['SERVER_NAME'] ?? null;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 meewog
Solution 2 tnavidi
Solution 3 Álvaro González