如果变量等于导航列表中的多个字符串

时间:2011-03-23 15:11:37

标签: php variables navigation if-statement operators

我发现了与此问题类似的内容,但它与字符串无关。我只是在寻找编写以下代码的最佳方法,我认为必须有一些我不知道的简短版本。

<ul id="top-nav">
    <li <?php if($filename == "index.php"){echo ("class=\"current\"");} ?>><a href="index.php" title="Home">Home</a></li>
    <li <?php if($filename == "cause.php"){echo ("class=\"current\"");} ?>><a href="cause.php" title="Cause">Cause</a></li>
    <li><a href="order.php" title="Order">Order</a></li>
    <li class="drop-down<?php if($filename == "grand-prize-one.php" | $filename == "grand-prize-two.php"){echo (" current");} ?>"><a href="grand-prize-one.php" title="Grand Prizes">Grand Prizes</a>
      <ul>
        <li><a href="grand-prize-one.php" title="Grand Prize One">Grand Prize One</a></li>
        <li><a href="grand-prize-two.php" title="Grand Prize Two">Grand Prize Two</a></li>
      </ul>
    </li>
    <li <?php if($filename == "early-bird.php"){echo ("class=\"current\"");} ?>><a href="early-bird.php" title="Early Bird">Early Bird</a></li>
    <li class="drop-down<?php if($filename == "vehicles.php" || $filename == "vacations.php" || $filename == "other-prizes.php"){echo (" current");} ?>"><a href="vehicles.php" title="Electronics &amp; more">Other Prizes</a>
      <ul>
        <li><a href="vehicles.php" title="Vehicles">Vehicles</a></li>
        <li><a href="vacations.php" title="Vacations">Vacations</a></li>
        <li><a href="other-prizes.php" title="Electronics &amp; more">Electronics &amp; more</a></li>
      </ul>
    </li>
    <li <?php if($filename == "winners.php"){echo ("class=\"current\"");} ?>><a href="winners.php" title="Winners">Winners</a></li>
  </ul>

是否有更短的方式来撰写$filename == "vehicles.php" || $filename == "vacations.php" || $filename == "other-prizes.php"?我怀疑我是否需要它来容纳更多5-10个可能的字符串。

谢谢

对于那些发现这个问题的人,我最终这样做了:

使用我的主要PHP

<?php
 // My other code
 $grandPrizes = array("grand-prize-one.php","grand-prize-two.php");
 $otherPrizes = array("vehicles.php","vacations.php","other-prizes.php");
?>

我在li元素中的内联PHP

<?php if (in_array($filename, $grandPrizes)) {echo " current";} ?>

4 个答案:

答案 0 :(得分:5)

$filenames = array("vehicles.php","vacations.php","other-prizes.php");
if (in_array($filename, $filenames)) {
    // code here
}

答案 1 :(得分:4)

您可以使用开关:

http://php.net/manual/en/control-structures.switch.php

switch($filename) {
    case "vehicles.php":
    case "vacations.php":
    case "other-prizes.php":
        echo "class=\"current\"";
        break;
}

答案 2 :(得分:2)

您可以使用

if(in_array($filename, array("vehicles.php", "vacations.php", "other-prizes.php"))){

答案 3 :(得分:2)

试试这个:

<?php 
    if(in_array($filename, array("vehicles.php", "vacations.php", "other-prizes.php")) {
        echo ("class=\"current\"");
    } 
?>

in_array函数适合您要执行的操作。