DEV Community

Eko Priyanto
Eko Priyanto

Posted on

php switch, if else alternative

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

Switch cara lama:

<?php
$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;
}
Enter fullscreen mode Exit fullscreen mode

Dengan cara PHP 8 yang lebih ringkas:

<?php
$statusCode = 200;

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

lebih mudah dan ringkas

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay