2012-11-14 18 views
0

我在我正在處理的投資組合網站的標題中有一個小的switch語句,它管理哪個鏈接顯示在哪個頁面上。 $ id的值來自GET變量,即 - '?id = index'。使用NOT運算符的PHP字符串開關

switch($id) { 
    case "index": 
     //Show links to content 
    case !"index": 
     //Show link to index 
    case !"about": 
     //show link to about page 
} 

問題是NOT運算符在最後兩種情況下不工作。我希望指向索引的鏈接在用戶不在索引頁上時顯示,同樣也在about頁面中顯示。目前,所有的鏈接索引頁上顯示時($ ID ==「指數),並沒有被任何其他頁面上顯示。

爲什麼會這樣呢?

+4

沒有開關的情況下不工作這種方式 – GBD

回答

3

之所以如此,是因爲它應該是如此。

switch使用==運營商進行比較。因此,在第二種情況下,你實際上是在測試是否

$id == (!"index") 

這將始終評估爲false,因爲任何字符串將true而不是真的會是false

這意味着,在你的情況下,最好使用ifelse

+0

我還是相當新的編程,具體是$ id ==!「index」和$ id之間的區別!=「index」? –

+0

'$ id!=「index」'測試'$ id'是否*不等於''index''。 '$ id ==!「index」'測試否定''index''(不管可能是什麼)等於'$ id'。 – Oswald

0

對不起,但您要做的僅僅是switch/case結構的無效語法。

最接近你要找的是使用default選項。這就像最後的case選項一樣工作,該選項處理前面case中沒有捕獲的所有值。

switch($id) { 
    case "index": 
     //Show links to content 
    case "about": 
     //Show link to about page 
    default: 
     //show link to default page. 
} 

而且 - 不要忘了break;在每個case塊的末尾,否則它會始終陷入下一個,這可能會導致一些意外的錯誤。

0

!"index"可能會評估爲false(不過我有點驚訝它沒有引起語法錯誤),你實際上就會有這樣的說法:

switch($id){ 
    case "index": //... 
    case false: // ... 
    case false: // ... 
} 

當你想使用switch,你」我們需要做的就是這樣:

switch($id){ 
    case "index": // ... 
    case "about": // ... 
    default: 
     // Additional statements here, note that $id != "index" is already covered 
     // by not entering into case "index" 
} 
+0

這是因爲PHP中的switch case是表達式,而不是標量值。甚至像case(substr($ foo,-2)。「bar」):'是有效的。 – FtDRbwLXw6

0

開關箱不接受複雜的表達式。不!運算符是邏輯運算符。它在像這樣的表達式中工作。

!$x; // true if $x = false 

或作爲比較操作者:

$a != $b; // Not equal 
// or 
$a !== $b // not identical 

從手冊。

switch語句的情況下,表達可以是其值是簡單類型的表達式 ,即,整數或浮點數 數字和字符串。數組或對象在這裏不能使用,除非它們被取消引用到一個簡單的類型。

0

你的代碼正在做的是將$ id與三個值進行比較:「index」,!「index」(不管它的意思)和!「about」。

我不確定你的方法。你應該嘗試if/else或者ternary操作符。

希望它有幫助。

0

交換機不提供自定義操作符。

switch ($id) { 
    case 'index': 
      // $id == 'index' 

      break; 

    case 'about': 
      // $id == 'about' 

      break; 

    case 'help': 
    case 'info': 
      // $id == 'info' or $id == 'help' 

      break; 

    default: 
      // all other cases 
} 
0

你一定可以解決這個問題:

switch($id){ 
    case ($id != 'index'): 
     echo 'this is not index'; 
     break; 
    case 'index': 
     echo 'this is index'; 
     break; 
    case 'foo': 
     echo 'this is foo!'; 
     break; 
    default: 
     break; 
} 

然而,這個例子是有缺陷的,因爲第一個case語句將正好趕上任何不屬於「索引」因此,你應該永遠不得到案例'富',也沒有默認聲明