2015-11-21 15 views
-1

我有一個奇怪的案例問題,在我的PHP代碼;PHP案件不能與整數

$sm_hours = (int)$sm_hours; // Make it an integer 

echo $sm_hours; // is 206 

    switch ($sm_hours) { 
     case ($sm_hours = 0 && $sm_hours <= 120): 
      echo "One"; 
     break; 
     case ($sm_hours >= 121 && $sm_hours <= 240): 
      echo "Two"; 
     break; 
     case ($sm_hours >= 241): 
      echo "Three"; 
     break; 
    } 

$ sm_hours是206,但我得到的回聲是One not Two。我錯過了什麼?

感謝

+0

嘗試使用intva($ sm_hours);而不是cast(int) – Cr1xus

+0

試試$ sm_hours> = 0 && $ sm_hours <= 120 –

+0

「=」是一個賦值運算符而不是比較運算符。 – Jinandra

回答

1

你總是會跳進第一開關的情況下,因爲你設置$sm_hours 0單=用於設置變量。

要測試其值使用==將執行type juggling或使用===也測試類型。

1
case ($sm_hours == 0 && $sm_hours <= 120): 

您使用相等運算

1

如果一個,試試這個:

case ($sm_hours == 0 && $sm_hours <= 120): 
    echo "One"; 
break; 
+0

非常感謝..我知道這很簡單,我只是看不到它! – HeavyHead

+0

在這種情況下,第一種情況下,只有當sm_hours爲0時才爲真 – swidmann

+0

@HeavyHead在0 <$ sum_hours <120時不起作用。試試吧 –

0

嘗試

$sm_hours >= 0 && $sm_hours <=120 
+0

你能解釋一下,爲什麼他的代碼不工作? – swidmann

+0

由於int是一個布爾值,所以switch語句被轉換爲switch(260(boolean))。在第一個語句中,$ variable被更新爲0,它返回一個布爾值true,當它與120比較時,它總是評估爲0 <120,因此布爾值變爲真,匹配發生,因此條件得到評估 –

+0

我以爲你會指向賦值而不是比較:'sm_hours = 0' – swidmann

1
你的情況

更好地使用if語句:

$sm_hours = (int)$sm_hours; // Make it an integer 
echo $sm_hours; // is 206 

if ($sm_hours >= 0 && $sm_hours <= 120) 
    echo "One"; 
elseif ($sm_hours >= 121 && $sm_hours <= 240) 
    echo "Two"; 
else 
    echo "Three"; 

交換機只是試圖匹配確切的值。

0

好吧,所以這項工作考慮到了Anand指出的$ sm_hours是< 120。此代碼適用於我需要的所有選項。

 switch ($sm_hours) { 
     case ($sm_hours >= 121 && $sm_hours <= 240): 
      echo "Two"; 
     break; 
     case ($sm_hours >= 241): 
      echo "Three"; 
     break; 
     default: 
      echo "One"; 
     break; 
    }