2012-03-01 107 views
0

這裏是我的代碼我應該使用&&或||

<?php 

if($_SERVER['REQUEST_URI']!="/index.php?task=join&" || $_SERVER['REQUEST_URI']!="/index.php?task=join&step=1" 
|| $_SERVER['REQUEST_URI']!="/index.php?task=join&step=2") { 
    include ("inc/js/script.php"); 
} 

?> 

我需要說「如果REQUEST_URI!= /index.php?task=join & '或' /index.php?task=join &步= 1 '或'/的index.php?任務=加入&步= 2 >>>包括INC/JS/script.php的

當我使用& &它正常工作,但我認爲正確的答案應該是||

是什麼請錯?

+0

聽過[德摩根定律](http://en.wikipedia.org/wiki/De_Morgan's_laws) – 2012-03-01 09:32:03

回答

2

||裝置or&&裝置and。如果or是你要什麼,使用||

但是,如果你使用||,病情會始終評估爲true,因爲$_SERVER['REQUEST_URI']總是會從"/index.php?task=join&""/index.php?task=join&step=1"無論是不同的,因爲它不能同時。

所以我想你實際上是在尋找一個and條件 - &&

此外,你應該使用strcmp用於字符串比較。

0

你想請求URI是:

一)不等於那些事(& &)

B)不等於一個或多個(或全部)的那些東西(||)

你想要& &我懷疑。

1

答案是&&,因爲你希望它是AND因爲你是比較相同的變量不等於不同的值。

希望變量是not this, not that, *AND* not the other

如果它使用OR||),那麼它可以是其中之一,但只要它不是全部(它顯然不能)。

3

像你想「AND」這聽起來我 - 或者你可以改變這一切的意義爲:

if (! (uri == first || uri == second || uri == third)) 

如果你仔細想想吧,URI不能既是「/指數。 ?PHP的任務=加入&「‘/index.php?task=join &步= 1’,所以它必須不等於他們的一個 - 在當前的代碼,以便使用||總是返回真。

1

如果我明白你想要什麼: 我會建議使用$ _GET和做它像這樣:

<?php 
if ($_SERVER["PHP_SELF"] == "/index.php" && $_GET['task'] == "join" && (isset($_GET['step'] && ($_GET['step'] == 1 || $_GET['step'] == 2))) 
include_once("inc/js/script.php"); 



?> 
+0

與Salman A的建議一樣,這是有缺陷的,因爲它允許其他請求參數存在,而原始代碼不 – 2012-03-02 03:27:51

1

你想要做什麼你的英文說明是好的,但是當你到了代碼,有一個翻譯錯誤。

這裏是你說你想要的行爲:

如果REQUEST_URI = /index.php?task=join & '或' /index.php?task=join &步= 1 '或' /index.php?task=join &步= 2 >>> 包括INC/JS/script.php的

當你這樣說的話,很明顯的是, 「不」(在!在!= )適用於所有的URI。所以讓我們打破了,不是和使用方括號來表示,它適用於一切:

如果不是(REQUEST_URI = /index.php?task=join &「或」 /index.php?task=join &步= 1 '或' /index.php?task=join &步= 2)>>> 包括INC/JS/script.php的

我們從英語讓我們到近代碼,我們只需要把事情說得更完整:

if ! (REQUEST_URI == /index.php?task=join& or 
     REQUEST_URI == /index.php?task=join&step=1 or 
     REQUEST_URI == /index.php?task=join&step=2) 
    include inc/js/script.php 

這實質上是Jon Skeet提出的解決方案。作爲進一步的說明,這裏是爲什麼你的代碼工作,如果你將|| s更改爲& & s。你已經基本上重新發現邏輯的衆所周知的規則叫德·摩根定律(在薩爾曼A的評論簡稱),它有兩種形式(其中「< ==>」的意思是「當且僅當」):

  1. !(A || B)< ==>!甲& &!乙
  2. !(A & & B)< ==>!甲|| !乙

據德·摩根定律的形式1,上面的代碼,因此是一樣的

if (!REQUEST_URI == /index.php?task=join& and 
     !REQUEST_URI == /index.php?task=join&step=1 and 
     !REQUEST_URI == /index.php?task=join&step=2) 
    include inc/js/script.php 

這是一樣的

if (REQUEST_URI != /index.php?task=join& and 
     REQUEST_URI != /index.php?task=join&step=1 and 
     REQUEST_URI != /index.php?task=join&step=2) 
    include inc/js/script.php 
相關問題