Search code examples
phpstringternary-operatoris-empty

Empty string not equal to empty string in PHP ternary operator expression


Could someone explain me the following?

$a="";

$a="" ? "" : "muh";

echo $a; 
// returns muh

Solution

  • It looks you are trying to use Comparison operator ==, but instead you are using an Assignment operator =

    Your code is trying to assign $a the result of the expression "" ? "" : "muh". An empty string is evaluated as false and $a is assgined the value of muh.

    Let's put some parentheses to make it more obvious:

    //$a equals (if empty string then "" else "muh")
    $a = ("" ? "" : "muh");
    
    echo $a; // muh
    
    
    //$a equals (if $a is equal to empty string then "" else muh)
    $a = ($a == "" ? "" : "muh"); 
    
    echo $a; //