0

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>';
Cœur
  • 37,241
  • 25
  • 195
  • 267
calljhon
  • 72
  • 2
  • 9
  • Can help this http://stackoverflow.com/questions/17981723/how-to-write-a-php-ternary-operator – b2ok Mar 18 '17 at 22:28
  • Just a quick thought. Just because you can do something, does not mean that you should - It can be all too easy to end up with an unreadable mess. Readability (and ease of understanding) is better in the long term. – Alister Bulman Mar 19 '17 at 10:30

3 Answers3

2

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.

Community
  • 1
  • 1
forrestmid
  • 1,494
  • 17
  • 25
1
echo '<div>
     '.((LoginCheck($this->db)) ? '
     <span class="option1"></span>
     ' : '
     <span class="option1"></span>
     ').'</div>';

Article about PHP ternary operator

Andrew Che
  • 928
  • 7
  • 20
-1

As much i understand you cannot use 'if-else' statement in 'echo'. You have to use reverse. You can use your 'echo' in 'if-else' statement. Below code might help you:


    $html = "&ltdiv&gt";

    if(LoginCheck($this->db) == true){
        $html .= "&ltspan class='option1'>&lt/span>";
    }else{
        $html .= "&ltspan class='option2'>&lt/span>";
    }

    $html .= "&lt/div>";

    echo $html

Ashish Tiwari
  • 1,919
  • 1
  • 14
  • 26