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 }?>
It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);
The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With