2009-09-02 56 views
0

在下面的PHP,如果我比较使用==它的工作原理,因为我希望它,如果我用!=然后我的代码休息,有人可以解释或帮助一个变量?PHP的if/else错误

$_GET['p'] = 'home'; 

// DOES NOT work, it will always return "show JS" regardless to what string I have 
if ($_GET['p'] != 'home' || $_GET['p'] != 'create.account'){ 
    echo 'show JS'; 
}else{ 
    echo 'do not show JS'; 
} 

// Works as I would expect it to 
if ($_GET['p'] == 'home' || $_GET['p'] == 'create.account'){ 
    echo 'do not show JS'; 
}else{ 
    echo 'show JS'; 
} 

回答

9

$ _GET ['p']不能同时是两个不同的东西。你说int是第一个表达式; p不在家或不是create.account。它总是如此。您应该使用& &而不是||

+0

伟大的作品 – JasonDavis 2009-09-02 22:42:54

+3

+1简单德摩根定律(http://en.wikipedia.org/wiki/Demorgan%27s_law) – 2009-09-02 22:44:14

0
if ($_GET['p'] != 'home' && $_GET['p'] != 'create.account') 
+0

因为http://en.wikipedia.org/wiki/Logical_disjunction 的误用(假或者真)==真 – balint 2009-09-02 22:45:12

2
(X != A) || (X != B) 
≡ !(X == A) || !(X == B) 
≡ !((X == A) && (X == B)) 

(X == A) && (X == B)永远是假的,因为条件A != BX不能同时AB在同一时间。因此!((X == A) && (X == B))(X != A) || (X != B)总是如此。

3

您可以通过DeMorgans Laws为否定看到问题

!(A || B) === (!A && !B) 

你给的解决方案是不可能的,因为没有办法让两个语句是假的,因为这将意味着该字符串相当于两个比较字符串。 else块将被击中的唯一方法是如果两者都是假的(由于OR语句)。