PHP Switch Statement

Php
47
November 19, 2024
11 Minutes

The PHP Switch statement is a control structure that determines which action to take based on different possibilities of a variable. It replaces multiple if-else blocks, making the code more readable and understandable. The switch statement is often used to run different blocks based on different values ​​of a variable.

Basic Structure of PHP Switch Statement

The basic structure of the PHP switch statement is as follows:

switch (variable) {
    case değer1:
        // Code to run if value matches 1
        break;
    case değer2:
        // Code to run if value matches 2
        break;
    case değer3:
        // Code to run if value matches 3
        break;
    default:
        // Code to run if no case matches
}
  • switch: Specifies the controlled variable.
  • case: Specifies the possible values ​​the variable can take.
  • break: When the condition matches, it makes the code stop at that point. If the break command is not used, the code continues to execute other case blocks (this situation is called "fall-through").
  • default: Specifies the code that will run for cases that do not match any case. This section is optional.

PHP Switch Statement Usage Examples

Simple Switch Expression

$colour = "kırmızı";

switch ($colour) {
    case "kırmızı":
        echo "Renk kırmızı.";
        break;
    case "yeşil":
        echo "Renk yeşil.";
        break;
    case "mavi":
        echo "Renk mavi.";
        break;
    default:
        echo "Bilinmeyen renk.";
}

In this example, when the $colour variable is "Kırmızı", "Renk kırmızı." message is printed on the screen.

Number Control with Switch Expression

$puan = 85;

switch (true) {
    case ($puan >= 90):
        echo "Harika! A+";
        break;
    case ($puan >= 80):
        echo "Başarılı! A";
        break;
    case ($puan >= 70):
        echo "İyi! B";
        break;
    case ($puan >= 60):
        echo "Geçer! C";
        break;
    default:
        echo "Maalesef, başarısız.";
}

Here, different evaluations are made depending on the value of the $puan variable. Using switch (true), each case condition contains a comparison.

Fall-through Example

$gun = 3;

switch ($gun) {
    case 1:
        echo "Pazar günü";
        break;
    case 2:
        echo "Pazartesi günü";
        break;
    case 3:
    case 4:
    case 5:
        echo "Hafta içi bir gün.";
        break;
    default:
        echo "Geçersiz gün.";
}

In this example, the same message is given for days 3, 4 and 5. The code between case 3:, case 4:, and case 5: is combined with the "fall-through" feature.

You can access this page faster by scanning the QR code.