PHP - Concatenate if statement?

两盒软妹~` 提交于 2019-12-17 19:52:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!