PHP Switch語句


PHP switch語句用於從多個條件執行一個語句。 它的工作原理像PHP的if-else-if語句。

語法

switch(expression){      
    case value1:      
         //code to be executed  
        break;  
    case value2:      
         //code to be executed  
         break;  
        ......      
    default:       
        code to be executed if all cases are not matched;    
}

PHP switch流程圖

PHP Switch範例程式碼

<?php    
    $num=20;    
    switch($num){    
        case 10:    
            echo("number is equals to 10");    
            break;    
        case 20:    
            echo("number is equal to 20");    
            break;    
        case 30:    
            echo("number is equal to 30");    
            break;    
        default:    
            echo("number is not equal to 10, 20 or 30");    
    }   
?>

執行上面程式碼得到以下結果 -

number is equal to 20