9

I am trying to do the following:

<li <?PHP ($this->pageName == 'index' ? ?>class="current"<?PHP : '')?>><a href="">Home</a></li>

But it is not working.

Is what I'm trying to achieve possible? If so what am I doing wrong?


I know it's not hard to put PHP in HTML lol. I was curious if a ternary operator could be used in a way that is similar to:

<?PHP if(1 == 1){?>
<p>Test</p>
<?PHP }?>
1
  • 1
    why make it simple when you can obfuscate it ? Commented May 6, 2013 at 20:08

3 Answers 3

11

What you have done will only RETURN the value "class='current'". You still will be required to ECHO/PRINT it to have it applied.

The code below should get it working fine.

<li class="<?PHP echo ($this->pageName == 'index')? 'current': ''; ?>">
    <a href="#">Home</a>
</li>

What I've just done here is place the class attribute outside of the php so as to keep things neater and ECHOed the value returned by ternary in this case "current", if the value evaluates to true.

For test purposes, you can try the line of code below toggling the values being compared.

<li class="<?PHP echo ( 1 == 0 )? 'current': ''; ?>">
    <a href="#">Home</a>
</li>
Sign up to request clarification or add additional context in comments.

Comments

2

Also, you can use PHP shorthand for this, I'm not exactly sure what youre trying to do, but have an idea, look at this code and see if you can figure it out:

<li <?=($this->pageName == 'index') ? "class='current'" : ''?>><a href="">Home</a></li>

everything in the parenthesis() is the if conditional\comparative. The

Comments

0
<li <?PHP ($this->pageName == 'index') ? ?> class="current" <?PHP : '' ?>><a href="">Home</a></li>

I doubt, what you are trying to do would even work, because the logic of the ternary operator is

if condition ? Yes/true : No/false ;

What replaces Yes/true in your code segment?

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.