php switch, if else alternative

Switch atau bahkan if, else apa masih dipakai? Switch cara lama:

Feb 23, 2025 - 06:43
 0
php switch, if else alternative

Image description
Switch atau bahkan if, else apa masih dipakai?

Switch cara lama:


$statusCode = 200;
$message = "";
switch ($statusCode) {
    case 200:
        $message = "OK";
        break;
    case 500:
        $message = "Internal Server Error";
        break;
    case 404:
        $message = "Not Found";
        break;
    default:
        $message = "Unknown Status Code";
        break;
}

Dengan cara PHP 8 yang lebih ringkas:


$statusCode = 200;

$message = match($statusCode){
    200 => "OK",
    500 => "Internal Server Error",
    404 => "Not Found",
    default => "Unknown Status Code"
};

lebih mudah dan ringkas