-3

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'];

Cian
  • 1
  • 1
  • 1
  • 1
    Well that depends a bit on what logic you're trying to implement (as per the two suggestions in the error message)... – ADyson Feb 25 '22 at 09:04
  • 1
    may be this will help you out! https://stackoverflow.com/questions/8735280/using-nested-ternary-operators – atomankion Feb 25 '22 at 09:06

3 Answers3

2

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

meewog
  • 1,690
  • 1
  • 22
  • 26
0

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

tnavidi
  • 1,043
  • 6
  • 12
0

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;
Álvaro González
  • 142,137
  • 41
  • 261
  • 360