Search code examples
phpif-statementconditional-statementsstatements

How to use if and else inside echo statement?


I've heard something about ternary operator but I kind of beginner and don't know how to use it, I'm trying to make this:

                   echo    '<div>
                           '.if(LoginCheck($this->db) == true):.'
                            <span class="option1"></span> 
                           '.else:.'
                           <span class="option1"></span>                             
                           '.endif;.'
                           </div>';

Solution

  • Yes the ternary operator is what you're looking for, but you have to chain them to get the if-else statement.

    echo '<div>'.(LoginCheck($this->db) == true ?
         '<span class="option1">' : '<span class="option2"></span>').'</div>'
    

    The evaluation statement comes before the question mark (?) and there is no if tag to put before the statement. It's just the expression to evaluate to true/false, and then the question mark, and then the first statement is if the expression is truthy, the second statement, separated from the first by a colon (:), is if the expression is not truthy.

    Look here for some more info.