比较2个字符串

时间:2011-11-07 16:51:17

标签: php string compare

我的php脚本运行不正常。

当我使用strcmp测试它时,它在正确的时间返回0,但if语句仍然返回false。

keywords.php的内容

<?php $cat_array = array("All Deals","Arts & Crafts","Automotive","Dental","Education & Training","Entertainment","Fashion","Fitness & Health","Floral","Fun & Adventure","Home & Garden","Pets","Photography","Restaurants","Spa & Beauty","Sports","Subscriptions","Tours & Attractions","Trade Shows","Travel","Workshops");
$cat_nav_array = array("alldeals","arts_crafts","automotive","dental","education_training","entertainment","fashion","fitness_health","floral","fun_adventure","home_garden","pets","photography","restaurants","spa_beauty","sports","subscriptions","tours_attractions","tradeshows","travel","workshops");

&GT;

主页的php代码

 <?php 
        require_once("keywords/keywords.php");
        $count = 0;
        $category = $_GET['category'];
        foreach ($cat_array as $link)
        {
            $count++;
        }
        for ($i = 0; $i <= $count; $i++)
        {
            $link = $cat_nav_array{$i};
            $text = $cat_array{$i};

            if ($category === $link) 
            {
            ?>
                <li><a class="ch_selected" href="<?php echo $_SERVER['HTTP_HOST']?>/chunky/others/?category=<?php echo $link?>" title="View all Deals from <?php echo $text ?>"><?php echo $text?></a></li>
            <?php 
            } 
            else
            {?>
                <li><a href="<?php echo $_SERVER['HTTP_HOST']?>/chunky/others/?category=<?php echo $link ?>" title="View all Deals from <?php echo $text ?>"><?php echo $text?></a></li>
            <?php
            }
        } ?>

工作代码:

    <?php 
        require_once("keywords/keywords.php");
        $count = 0;
        $category = strtolower($_GET['category']);
        foreach ($cat_array as $link)
        {
            $count++;
        }
        for ($i = 0; $i <= $count; $i++)
        {
            $link = $cat_nav_array{$i};
            $text = $cat_array{$i};

            $same = strcmp($link, $category);

            if ($same != 0) 
            {
            ?>
                <li><a href="<?php echo $_SERVER['HTTP_HOST']?>/chunky/others/?category=<?php echo $link?>" title="View all Deals from <?php echo $text ?>"><?php echo $text?></a></li>
            <?php 
            } 
            else
            {?>
                <li class="ch_selected"><a href="<?php echo $_SERVER['HTTP_HOST']?>/chunky/others/?category=<?php echo $link ?>" title="View all Deals from <?php echo $text ?>"><?php echo $text?></a></li>
            <?php
            }
        } ?>

3 个答案:

答案 0 :(得分:2)

if ($catagory === $link)比较。

答案 1 :(得分:0)

尝试在if行之前做一个var_dump($link, $catagory),看看两个变量是否真的相同。

答案 2 :(得分:0)

我可能会离开答案,但如果我没记错,那不是比较字符串的方法。 请参阅:http://www.phpcatalyst.com/php-compare-strings.php