Search code examples
phpternary-operatorclamp

How does this nested ternary expression work?


I was making a clamp() function in php, and decided to go for a nested ternary expression just to try it. In the end, I settled with this (working) function :

function clamp($value, $min, $max){
    return 
          $value<$min ? $min
        : ($value>$max ? $max
        : $value);
}

However, why are the brackets around the second expression required? I had tried removing them afterward :..

function clamp($value, $min, $max){
    return 
          $value<$min ? $min
        : $value>$max ? $max
        : $value;
}

... but in this version, it will return $max if $value is smaller than $min. I just don't understand how it comes to that result.


Solution

  • I had hear of php having "left associativity" with ternary, though I never understood what it meant:

    Take
    $bool ? "a" : $bool ? "b" : "c"
    Right associativity is: $bool ? "a" : ($bool ? "b" : "c")
    Left associativity is : ($bool ? "a" : $bool) ? "b" : "c"
    So in the end php will always it evaluate to either b or c.

    Bonus:
    $bool ? $bool ? "c" : "b" : "a"
    Here is a syntax that I think wouldn't change meaning based on associativity. I wonder whether people managed to find a pretty indentation for this variant.