WordPress PHP If statement inside assignment

Quick simple question, is it possible to do an if statement inside of a php assignment statement so that you can switch what would be assigned?

IE: Inside of a wordpress PHP function that already works

Read More
$example.='

<div id="test-'.$num.'">
    <a href="http://google.com">Google</a>
</div>';

The following doesn’t work (gives an IF parse error)

$example.='

<div id="test-'.$num.'">
    'if($num == 2)'
        <a href="http://yahoo.com">Yahoo</a>
    'else' <a href="http://google.com">Google</a>
</div>';

Related posts

Leave a Reply

3 comments

  1. instead you could have done:

    $aText = ($num == 2) ? '<a href="http://yahoo.com">Yahoo</a>' : '<a href="http://google.com">Google</a>';
    $example.='    
    <div id="test-'.$num.'">
        '.$aText.'
    </div>';
    
  2. You can concatenate the code:-

    $example.='
    <div id="test-'.$num.'">';
        if($num == 2){
           $example.=' <a href="http://yahoo.com">Yahoo</a>';
        }else {
           $example.='<a href="http://google.com">Google</a></div>';
        }
    
  3. check the code:

    $example.='<div id="test-'.$num.'">';
            if($num == 2)
                $example.= '<a href="http://yahoo.com">Yahoo</a>';
            else 
                $example.='<a href="http://google.com">Google</a>';
        $example.='</div>';