What's wrong with this ternary operator?

≯℡__Kan透↙ 提交于 2020-01-03 02:28:05

问题


I use a paging system like this:

<?php
$p = $_GET['p'];

switch($p)
{
    case "start":
        $p = "pages/start.php";
        $currentPageId = 1;
    break;

    case "customers":
        $p = "pages/customers.php";
        $currentPageId = 2;
    break;

    default:
        $p = "pages/start.php";
        $currentPageId = 1;
    break;
}
?>

I want to set css class="active" to the menu item of the page i'm on.

It works if I print <li> items like this:

<li><a href="?p=start" <?php if ($currentPageId == 1) {echo "class='active'";}else {} ?>>Start</a></li>

But I would like to use ternary operator instead. I tried this code but it doesn't work:

<li><a href="?p=start" <?php ($currentPageId == '1') ? 'class="active"' : '' ?>>Startsida</a></li>

Any idea why?

EDIT So the problem was I was missing an echo. Now let me extend the question a bit...

I need to encapsulate my entire <ul> inside the <?php ?> tags. So what I would like is something like this:

echo "<div id='nav'>";
 echo "<ul>";

   echo "<li><a href='?p=start' /* ternary operator to match if the page I'm on is equal to $currentPageId as defined in the paging system (above), if so set class='active' else do nothing*/>Start</a></li>;
   echo "<li><a href='?p=customers' /* ternary operator to match if the page I'm on is equal to $currentPageId as defined in the paging system (above), if so set class='active' else do nothing*/>Customers</a></li>;


 echo "</ul>";
echo "</div>";

I need to do this because I will display the links based on ifstatements.. "if user is admin display this link, else don't" ... Anyone got a solution?


回答1:


You are missing an echo:

<li><a href="?p=start" <?php echo (($currentPageId == '1') ? 'class="active"' : '') ?>>Startsida</a></li>

That should do the trick.


Addressing the second question:

<?php
if($something == true) {
    echo "<div id='nav'>"."\n<br>".
            "<ul>"."\n<br>".
                '<li><a href="?p=start"'. (($currentPageId == '1') ? 'class="active"' : '') .'>Startsida</a></li>'."\n<br>".
                '<li><a href="?p=customers" '. (($currentPageId == '1') ? 'class="active"' : '') .' >Customers</a></li>'."\n<br>".
            "</ul>"."\n<br>".
            "</div>"."\n<br>";
}
?>



回答2:


As others have pointed out, you were missing echo. I also wanted to point out that you don't even need a ternary operator in this case because you aren't doing anything in the else case:

<li><a href="?p=start" <?php if ($currentPageId == '1') echo 'class="active"'; ?>>Startsida</a></li>


来源:https://stackoverflow.com/questions/11075939/whats-wrong-with-this-ternary-operator

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