简体   繁体   中英

What's wrong with this ternary operator?

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 if statements.. "if user is admin display this link, else don't" ... Anyone got a solution?

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>";
}
?>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM