1

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

$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>';

3 Answers 3

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>';
Sign up to request clarification or add additional context in comments.

1 Comment

This is a smart way of doing this, I'm going to implement this real quick and see if it works as I expect.
1

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>';
    }

2 Comments

Is there anyway to do it without reassigning the $example.=? The real code is nested a couple of tags down and I would rather see if its possible before going in and separating them. Your way does work though
in string concatenation - the answer is no, because of we can't use any conditional operator with in string assignment.
0

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.