PHP is one of the conditional expressions. PHP Switch Case What is it and how is it used? In this lesson PHP Switch Case We will cover the topic.

PHP Switch Case expression PHP if else It is used to execute code based on different conditions, such as expression. We will see the syntax in the example below.

switch (n) {
  case label1:
     //n=label1'e eşitse çalıştırılacak kodlar
    break;
  case label2:
    //n=label2'e eşitse çalıştırılacak kodlar
    break;
  case label3:
    //n=label3'e eşitse çalıştırılacak kodlar
    break;
  default:
    //n hiçbir label'e eşit değilse çalıştırılacak kodlar
}

PHP Switch Case works like this: First, we have an expression (which is most often a variable) that is evaluated once. The value of the expression is compared with the value in each structure. If it matches a value in a structure, the code block in that structure is executed. If no value matches, the code block in the default statement is executed. The break statement is used to prevent the code from automatically entering the next structure.

PHP Switch Case Examples

Now let's do a real example. We can replace n in the previous example with a variable, and replace label1 with data. Whichever label the variable we substituted for N is equal to, that code block will be executed. If it is not equal to any of them, the default code block under default will be executed.

$favorite_movie = 'the matrix';
switch ($favorite_movie) {
  case 'inception':
    echo 'Favori filmin: inception';
    break;
  case 'the matrix':
    echo 'Favori filmin: the matrix';
    break;
  case 'v for vendetta':
    echo 'Favori filmin: v for vendetta';
    break;
  default:
    echo 'Favori filmin yok';
}
// Çıktı: Favori filmin: the matrix

We made a real example above. Now let's do another example to reinforce what we have learned.

$lucky_number = null;
switch ($lucky_number) {
  case 4:
    echo 'Favori sayı: 4';
    break;
  case 6:
    echo 'Favori sayı: 6';
    break;
  case 8:
    echo 'Favori sayı: 8';
    break;
  default:
    echo 'Favori sayı yok';
}
// Çıktı: Favori sayı yok

PHP Switch Case Alternative Syntax

We learned in the previous lesson that we can use alternative syntax in PHP conditional statements. In the last part of this lesson PHP Switch Case We will learn alternative syntax.

$number = 3;
switch ($number): 
     case 1: 
    	echo 'number is 1';
        break;
     case 2: 
    	echo 'number is 2';
        break;
     case 3: 
    	echo 'number is 3';
        break;
     default:
        echo 'number is null';   
endswitch;
// Çıktı: number is 3

PHP Switch CaseIn the alternative syntax, instead of opening curly brackets after the switch, we put a colon. PHP Switch Case endswitch; instead of closing the curly brackets when the expression ends; We use the expression.

After seeing the difference between switch and match, ternary and null coalescing operators are the continuation of my short article; order PHP lessons on the page.