Heim  >  Artikel  >  Backend-Entwicklung  >  PHP-Switch-Anweisung

PHP-Switch-Anweisung

王林
王林Original
2024-08-29 12:40:39781Durchsuche

If we talk in generic coding terminologies, then being a novice to coding, you would have seen an “if” statement to handle condition checks and do some action on their validations; now let’s take a case that you are writing logic for traffic light systems design and if you look to proceed with the standard if conditions then probably you would end up with one “if”, one “else if or if” and one “else” statement, and if any other synonymous kind of business logic appears where such criteria are high in number. The code won’t appear good if they belong to the same category. For that, we have a “switch” statement, where you need to write this statement once only and describe certain cases associated under a common category and business logic to be implemented in association with that.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Detailed Description of PHP Switch Statement

Let’s see a PHP snippet where we have a range of age, and a corresponding message is displayed to represent those people’s categories.

$age = '7-12'
switch($age)
{
case '0-1': echo 'it is a baby';
break;
case '2-3' : echo 'toddler';
break;
case '4-6' : echo 'infant';
break;
case '7-12': echo 'child';
break;
default : echo 'others';
}
  • So you may have got a rough idea after seeing the example displayed above; the example carries the implementation of such a condition using just one ‘switch’ statement rather than putting ourselves into multiple if and else statements.
  • The Switch takes a common criterion parameter as input, which will take a set of values upon which we must apply the conditional evaluation for business logic implementation.
  • As in the above case, the age variable shows that the age range mentioned matches’ 7-12′, so we will get ‘child’ in the output.
  • Now let’s examine the processing order and the elapsed time in the control traversal. Given the input of the age variable, the system evaluates the case expression values against the test value and checks the first case. If the condition is not met, the control proceeds to the following statement, evaluate the following expression and continues searching until it finds the relevant expression.
  • Once it evaluates its test value, the system executes the ‘echo ‘child” statement and proceeds to the next step.
  • Will the control flow default also? As it seems something like a condition that will get executed by default. Well, it is not so. You must see that there is a ‘break’ statement in every case statement block, too; the task of ‘break’ is to take the flow out of the switch context and proceed with the next logical instruction in the program file.
  • The default statement executes only if none of the abovementioned conditions are met. For example, if the age is 24, the output will be ‘others’.
  • Hence it’s logical to place the default statement at the end of the file.
  • This order of placement matters a lot while you write code, and you should be well aware of the kind of input data that you will be getting mostly as a test condition; its better to keep that case at the top so that maximum users get the result as early possible with first line only. This could be done after data analysis in the system you are deploying.
  • Consider why there is no break in the default statement; the above description carries the answer although.

Syntax 

switch (testvalue) {
case label1:
code to be executed if testvalue = label1;
break;
case label2:
code to be executed if testvalue = label2;
break;
case label3:
code to be executed if testvalue = label3;
break;
default:
code to be executed if testvalue is different from above;
}

We have already shared a program in the above section on this logic only; refer to that for a better understanding of a use case.

Flow Chart for Switch

The flow chart for the PHP switch is the same as other coding languages’ switch statements, as this is common functionality in every language.

PHP-Switch-Anweisung

Examples

Kindly refer to the example shared in the details section, which carries detailed information about working, and let’s take some application use cases here for better clarity of the picture.

Use Case 1

Let’s say you are gathering the data related to students who have birthdays in each of the respective months of the calendar year; Here, you can include a month as a switch criteria and create 12 different arrays to store data of students corresponding to each month. As the condition is met, you can continuously add data to each of the arrays. All the arrays will likely become occupied by a total of 5000 students in a school.

Anwendungsfall 2

Sprechen wir über den Entwurf eines Taschenrechners im kleinen Maßstab, bei dem Sie Additions-, Subtraktions- und Multiplikationsoperationen ausführen müssen; In einem Schalter können Sie den Namen des Vorgangs übernehmen, ihn anhand von Fallbezeichnungen validieren, und sobald er erfüllt ist, gibt die dortige Geschäftslogik den Wert der Ausgabe basierend auf entsprechenden Berechnungen zurück.

Fazit

Wir haben Fälle gesehen, in denen die Anzahl der Bedingungen für eine Kategorie zunahm; dann ist es besser, die Anpassung mit einer switch-Anweisung vorzunehmen; Es macht den Code klarer und lesbarer und kann ihn auch schnell machen, basierend auf der Datenanalyse und der entsprechenden Platzierung der Logik. Wir haben beispielsweise die Syntax für die Implementierung in PHP und einige relevante Anwendungsfälle gesehen.

Das obige ist der detaillierte Inhalt vonPHP-Switch-Anweisung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:elseif in PHPNächster Artikel:elseif in PHP