2010-08-05 100 views
0

嗨,我不知道我可能会做错什么。我有两个条件返回true或false.For同样的原因它不工作。如果有人指出我可能会做错什么,我将不胜感激。PHP if语句?

<?php 
    $pagetype = strpos($currentPage, 'retail'); 
    if(isset($quoterequest) && $pagetype === True && $currentPage !== 'index.php'){ 
    echo "this is retail" ; 
    }elseif(isset($quoterequest) && $pagetype === False && $currentPage !== 'index.php'){ 
    echo "this is restaurant"; 
    }        
?> 

EDIT-对不起,我编辑它,但没有出现某种原因。基本上脚本眺望网址术语“零售”,如果它发现它,它应该返回“这是散户”,如果不是“这是餐厅”

quoterequest是就像这样

$quoterequest = "washington" 

和可变当前页面是从

<?php $currentPage = basename($_SERVER['SCRIPT_NAME']); 

只是要清楚。链接结构,像这样

www.example.com/retail-store.php www.example.com/store.php

+1

发生了什么,你想在这里发生什么?它没有进入你期望的条款,还是没有进入任何一个? – 2010-08-05 20:05:02

+0

我们可以得到一些$ currentPage和$ quoterequest的价值样本 – Phliplip 2010-08-05 20:05:22

+1

并且它是否说'这是零售'或'这是餐厅' - 或者都不是? – Phliplip 2010-08-05 20:06:15

回答

6

$pageType从不为真。如果包含该字符串,则strpos返回一个整数。所以测试!== false

<?php 
    $pagetype = strpos($currentPage, 'retail'); 
    if (isset($quoterequest) && $currentPage !== 'index.php') { 
     if ($pagetype !== false) { 
      echo "this is retail"; 
     } 
     else { 
      echo "this is restaurant"; 
     } 
    }      
?> 
1

起初看起来应该是$网页类型!==虚假
strpos返回从php.net/strpos

假或上匹配的数值

报价返回位置为整数。如果找不到指针,则strpos()将返回布尔值FALSE。

因此,要检查值是否没有找到,你应该使用if(strpos(...)=== false)并检查是否发现你应该使用if(strpos(...)!==假)

1

每次重复条件都没有意义。下面的代码应该做你想做的事情(考虑到上述strpos注释)。

$pagetype = strpos($currentPage, 'retail'); 
if($currentPage !== 'index.php' && isset($quoterequest)){ 
    if ($pagetype === false){ 
    echo "restaurant"; 
    }else{ 
    echo "retail"; 
    } 
} 
+1

dang我需要输入更快...... :) – Doon 2010-08-05 20:18:21

0

PHP有懒惰的评价。如果if语句中的第一项评估为false,它将停止评估其余代码。如果isset($quoterequest)的评估结果为false,则不会检查您的任何陈述中的其他内容。

$> 
<?php 

function untrue() { 
     return FALSE; 
} 

function truth() { 
     echo "called " . __FUNCTION__ . "\n!"; 
     return TRUE; 
} 

if (untrue() && truth()){ 
     echo "Strict.\n"; 
} else { 
     echo "Lazy!\n"; 
} 

$> php test.php 
Lazy!