Konstruksi case
Konstruksi case adalah sebahagian daripada pengendali switch dan membolehkan pengaturcaraan pencabangan bergantung pada nilai pembolehubah. Setiap case menyemak kesesuaian nilai pembolehubah dengan syaratnya dan melaksanakan kod jika kesesuaian ditemui.
Sintaks
switch ($variable) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default:
// default code
}
Contoh
Contoh mudah penggunaan konstruksi case untuk menyemak nilai nombor:
<?php
$num = 2;
switch ($num) {
case 1:
echo 'Satu';
break;
case 2:
echo 'Dua';
break;
default:
echo 'Nombor lain';
}
?>
Keputusan pelaksanaan kod:
'Dua'
Contoh
Penggunaan beberapa case untuk satu blok kod:
<?php
$char = 'b';
switch ($char) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
echo 'Vokal';
break;
default:
echo 'Konsonan';
}
?>
Keputusan pelaksanaan kod:
'Konsonan'
Contoh
Penggunaan case dengan rentetan:
<?php
$day = 'Monday';
switch ($day) {
case 'Monday':
echo 'Hari pertama minggu';
break;
case 'Friday':
echo 'Hari bekerja terakhir';
break;
default:
echo 'Hari biasa';
}
?>
Keputusan pelaksanaan kod:
'Hari pertama minggu'