PHP - Concatenate if statement?

13,484

Solution 1

Like this, using the ternary operator:

echo "<li class='". (($_GET["p"] == "home") ? "active" : "") . "'><a href='#'>Home</a>        </li>";  

Solution 2

echo "<li class='".(($_GET["p"] == "home") ? "active" : "")."'><a href='#'>Home</a>        </li>";

Solution 3

Do like this:

echo "<li class='".($_GET["p"] == "home" ? 'active' : '') ."'><a href='#'>Home</a>        </li>";

Solution 4

Instead of messy inline concatenations, might I suggest getting cozy with printf()?

$format = '<li class="%s"><a href="#">Home</a>        </li>';
printf($format, ($_GET['p'] == 'home') ? 'active' : '');
Share:
13,484

Related videos on Youtube

Necro.
Author by

Necro.

Updated on July 06, 2022

Comments

  • Necro.
    Necro. almost 2 years

    I want to concatenate in the middle of an echo to write an if statement, is this possible? Here is what I have.

    echo "<li class='".if ($_GET["p"] == "home") { echo "active"; }."'><a href='#'>Home</a>        </li>";
    
    • Michael Berkowski
      Michael Berkowski over 11 years
      You want a ternary. echo "<li class='". (($_GET["p"] == "home") ? "active" : "") ."'><a href='#'>Home</a></li>";