Kontrol Alur — PHP

PHP memiliki beberapa cara untuk mengontrol alur program. if / elseif / else: $nilai = 85; if ($nilai >= 90) { echo "A"; } elseif ($nilai >= 80) { echo "B"; } e

PHP memiliki beberapa cara untuk mengontrol alur program.

if / elseif / else:

$nilai = 85;

if ($nilai >= 90) {
    echo "A";
} elseif ($nilai >= 80) {
    echo "B";
} elseif ($nilai >= 70) {
    echo "C";
} else {
    echo "D";
}

Ternary operator:

$status = ($umur >= 17) ? "Dewasa" : "Anak-anak";

Null coalescing (??):

$nama = $input ?? "Guest";
// Jika $input null/undefined, gunakan "Guest"

Switch:

switch ($hari) {
    case "Senin":
        echo "Awal minggu";
        break;
    case "Jumat":
        echo "TGIF!";
        break;
    default:
        echo "Hari biasa";
}

Match (PHP 8+):

$pesan = match($role) {
    "admin" => "Akses penuh",
    "editor" => "Bisa edit",
    "user" => "Bisa baca",
    default => "Tidak dikenal",
};

match vs switch — beda penting:

Aspek match switch
Perbandingan Strict === Loose ==
Return value Ya (expression) Tidak
Fall-through Tidak ada Bisa (perlu break)
Exhaustive Wajib (atau UnhandledMatchError) Tidak

Contoh beda strict vs loose:

$x = "1";

// switch → loose compare: "1" == 1 bernilai TRUE
switch ($x) {
    case 1:  echo "int satu"; break;  // ← ini yang jalan
    case "1": echo "string satu"; break;
}
// Output: "int satu"

// match → strict compare: "1" !== 1
match ($x) {
    1   => "int satu",
    "1" => "string satu",  // ← ini yang cocok
};
// Return: "string satu"

Kapan pakai apa?

Yang akan kamu pelajari