2010-08-05 98 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!