Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline PHP / HTML Ternary If

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 }?>
like image 857
imperium2335 Avatar asked May 06 '13 19:05

imperium2335


People also ask

How use ternary operator in if condition in 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);

Does PHP support ternary operator?

The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

Is null ternary operator PHP?

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.


2 Answers

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>
like image 86
Chuks Avatar answered Sep 20 '22 05:09

Chuks


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

like image 32
half-fast Avatar answered Sep 23 '22 05:09

half-fast