问题
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>";
回答1:
Like this, using the ternary operator:
echo "<li class='". (($_GET["p"] == "home") ? "active" : "") . "'><a href='#'>Home</a> </li>";
回答2:
Do like this:
echo "<li class='".($_GET["p"] == "home" ? 'active' : '') ."'><a href='#'>Home</a> </li>";
回答3:
echo "<li class='".(($_GET["p"] == "home") ? "active" : "")."'><a href='#'>Home</a> </li>";
回答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' : '');
来源:https://stackoverflow.com/questions/13572117/php-concatenate-if-statement