phpshorthand-if

shorthand if explanation ? mark operator


For a template engine I would like to use shorthand if condition. I need to check if a value is != null print out some line if true. What I tried:

echo "test" ($user->affiliate_id !=null) ?   

I have no idea what to write behind the ?.


Solution

  • The line $someVariable = $condition ? $valueA : $valueB is equivalent to:

    if ( $condition ) {
        $someVariable = $valueA;
    }
    else {
        $someVariable = $valueB;
    }
    

    So, basically, if the condition is TRUE, $someVariable will take the first value after the ? symbol. If FALSE, it will take the second value (the one after the : symbol).

    There's a special case where you can not define the first value and it is like this: $someVariable = $someValue ?: $someOtherValue. It's equivalent to:

    if ( $someValue ) {
        $someVariable = $someValue;
    }
    else {
        $someVariable = $someOtherValue;
    }
    

    So, if $someValue evaluates to TRUE (any value different than 0 is evaluated to TRUE), then $someVariable will catch that value. Otherwise, it will catch $someOtherValue.

    To give you an example:

    function printGender( $gender ) {
        echo "The user's gender is: " . ( $gender == 0 ? "Male" : "Female" );
    }
    
    printGender(0); // Will print "The user's gender is: Male"
    printGender(1); // Will print "The user's gender is: Female"
    

    Another example:

    function printValuesStrictlyDifferentThanZero( $value ) {
        echo "Value: " . ( $value ?: 1 );
    }
    
    printValuesStrictlyDifferentThanZero(0); // $value evaluates to FALSE, so it echoes 1
    printValuesStrictlyDifferentThanZero(1); // $value evaluates to TRUE, so it echoes that $value
    

    EDIT:

    The operator ?: is NOT called the ternary operator. There are multiple ways to define a ternary operator (an operator that takes three operands). It is a ternary operator, but not the ternary operator. Some people just call it the ternary operator because they're used to do it and, probably, it's the only ternary operator vastly known in PHP, but a ternary operator is way more general than that.

    It's name is the conditional operator or, more strictly, the ternary conditional operator.

    Let's suppose I define a new operator called log base that evaluates, inline, if the logarithm of a number $A with base $C equals to $B, with its syntax like $correct = $A log $B base $C and it returns TRUE if the logarithm is right, or FALSE if it's not.

    Of course that operation is hypothetical, but it is a ternary operator, just like ?:. I'm gonna call it the logarithm checker operator.