2017-10-13 162 views
1

所以我寫了for循環,如下所示,出於某種原因,第一次循環後,循環停止。在這種情況下,我試圖通過發送值4,並且它失敗了從checkRes函數檢查字符串「true」的if語句。就是那個函數所做的就是返回字符串。這是我對循環的理解,它將繼續循環直到頂部的語句被滿足,或者退出。 我在下面做錯了什麼?
For循環在第一次迭代後不會繼續

// assume $avaliable = 4; 
for ($i=$avaliable;10>$i;$i++) { 
    $check = checkRes($i, $people_no, $booking_date); 
     if ($check === "true") { 
      switch($i) { 
       case 0: $newResTime = "6 PM"; break; 
       case 1: $newResTime = "6:30 PM"; break; 
       case 2: $newResTime = "7 PM"; break; 
       case 3: $newResTime = "7:30 PM"; break; 
       case 4: $newResTime = "8 PM"; break; 
       case 5: $newResTime = "8:30 PM"; break; 
       case 6: $newResTime = "9 PM"; break; 
       case 7: $newResTime = "9:30 PM"; break; 
       case 8: $newResTime = "10 PM"; break; 
       case 9: $newResTime = "10:30 PM"; break; 
       case 10: $newResTime = "11 PM"; break; 
      } 
      // Replace next line with your return from the chatbot 
      echo "We're sorry, that time isn't avaliable, but a reservation at $newResTime has been made!"; 
      exit; 
     } 
    } 
+2

刪除您'退出;'' – aldrin27

+0

$ check'是真實的,所以它進入'if'並在其上你有一個'退出;'所以這使得環路停止 – GEPD

+0

這段代碼很瘋狂。爲什麼你的check res函數只返回一個bool?爲什麼不直接返回時間?迭代指數與某人的預訂有什麼關係? – Rafael

回答

2

您正在用exit爲 「默認」 的解決方案。但它總是終止程序的執行(因爲這是exit所做的)。

而是做到這一點

switch($i) { 
    case 0: $newResTime = "6 PM"; break; 
    case 1: $newResTime = "6:30 PM"; break; 
    case 2: $newResTime = "7 PM"; break; 
    case 3: $newResTime = "7:30 PM"; break; 
    case 4: $newResTime = "8 PM"; break; 
    case 5: $newResTime = "8:30 PM"; break; 
    case 6: $newResTime = "9 PM"; break; 
    case 7: $newResTime = "9:30 PM"; break; 
    case 8: $newResTime = "10 PM"; break; 
    case 9: $newResTime = "10:30 PM"; break; 
    case 10: $newResTime = "11 PM"; break; 
    default: echo "..."; break; 
+0

這不起作用,因爲程序從未將它傳遞給switch語句,因爲$ check沒有計算爲真,所以它從來沒有使它在if語句中退出。即使它確實如此陳述,我也沒有看到回聲 –