2015-04-06 200 views
1

有沒有寫這個的沒有更好的辦法:更好的方式,如果else語句

if (in_array('WIN_WAITING', $statuses)) { 
    $this->globalStatus = 'WIN_WAITING'; 
} else if (in_array('IN_PLAY', $statuses)) { 
    $this->globalStatus = 'IN_PLAY'; 
} else if (in_array('WON', $statuses)) { 
    $this->pay($this->tickets['ticketID']); 
    $this->globalStatus = 'WON'; 
} else if (in_array('PAYEDOUT', $statuses)) { 
    $this->globalStatus = 'PAYEDOUT'; 
} else if (in_array('CLOSED', $statuses)) { 
    $this->globalStatus = 'CLOSED'; 
} else if (in_array('LOST', $statuses)) { 
    $this->globalStatus = 'LOST'; 
} else if (in_array('OPEN', $statuses)) { 
    $this->globalStatus = 'OPEN'; 
} 
+1

您可以通過將'pin'存儲在'array'中並使用'foreach'循環來減少'if'' else – 2015-04-06 13:38:05

+1

另外:'PAYEDOUT'應該是'PAIDOUT' - 另一個不錯的英語拼寫規則! – halfer 2015-04-06 13:38:49

回答

3

這應該爲你工作:通過所有的搜索字符串,如果

(這裏我只環路我發現我跳出循環)

<?php 

    $search = ["WIN_WAITING", "IN_PLAY", "WON", "PAYEDOUT", "CLOSED", "LOST", "OPEN"]; 

    foreach($search as $v) { 
     if(in_array($v, $statuses)) { 
      if($v == "WON") $this->pay($this->tickets['ticketID']); 
      $this->globalStatus = $v; 
      break; 
     } 

    } 

?> 
+0

你忘了'WON'的條件;) – 2015-04-06 13:38:54

+0

@AkramFares感謝您的通知,更新了我的回答 – Rizier123 2015-04-06 13:40:11

+0

@AkramFares:我認爲這可以留給OP':-)' – halfer 2015-04-06 13:40:14

2

也許像

$options = array('WIN_WAITING', 'IN_PLAY', 'WON', 'PAYEDOUT', 'CLOSED', 'LOST', 'OPEN'); 

for($i=0; $i<=7; $i++) { 

if(in_array($options[$i], $statuses)) { 
    $this->globalStatus = $options[$i]; 
    break; 
} 

} 

未測試,只是一個想法