Php switch statement expression value. Conditions in PHP

Hi all! Another PHP lesson has arrived. Today's topic is one of the most favorite among those who start programming. Of course, because conditions in PHP are what allow us to compose various algorithms. It is depending on the conditions that the program will behave one way or another. And it is thanks to them that we can get different results with different input data. PHP has several constructs that can be used to implement conditions. All of them are used and have their advantages in different situations, or, if you like, conditions. There are the same conditions all around, right? So. No one will argue that in real life, depending on the circumstances, we act differently. In programming this is no less important and now we will learn it.

As you should remember from the last lesson, in PHP, depending on the operator, the operands are cast to a specific type. For conditional operators in PHP, the same rules apply, and here the operand is always cast to a boolean value. In case this value true, then we consider that the condition is met, and if false– that condition is not met. Depending on whether the condition is met, we can do or not do some action. And here I propose to consider the first conditional operator - if.

Conditional if statement

This is the simplest and most frequently used operator. In general, the design looks like this:

And in real life, using the operator if as follows:

Here we have explicitly passed the value to the operator true. Of course, this is absolutely pointless. Let's use a condition to determine numbers greater than 10. It's quite simple:

10) ( echo "The number is greater than 10"; )

And after running we will see the result:

Number greater than 10

if-else construct

Is it possible to make it so that when the condition is not met, other code is executed? Of course you can! To do this, together with the operator if use the operator else(in Russian - otherwise). It is written after the curly braces that enclose the code that is executed when the condition is met. And the design looks like this:

10) ( echo "The number is greater than 10"; ) else ( echo "The number is less than or equal to 10"; )

Here again a message will be displayed on the screen:

Number greater than 10

However, if we change the input data, and the variable $x at the very beginning we assign the value 8 , the message will be displayed:

Number less than or equal to 10

Try this right now.

if-elseif-else construct: multiple conditions

In case you need to check multiple conditions, after the operator if the operator is also added elseif. It will check the condition only if the first condition is not met. For example:

10) ( echo "The number is greater than 10"; ) elseif ($x == 10) ( echo "The number is 10"; )

In this case, the screen will display:

The number is 10

And yes, after this operator you can add else. The code inside it will be executed if none of the conditions are met:

10) ( echo "The number is greater than 10"; ) elseif ($x == 10) ( echo "The number is 10"; ) else ( echo "The number is less than 10"; )

The result of this code, I believe, does not need to be explained. Yes, by the way, a whole list of elseif-s. For example, like this:

Casting to boolean

Remember, in the lesson about we learned how to explicitly cast values ​​to some type. For example:

The result will be true.
Working the same way, only the implicit conversion always occurs in the condition. For example, the following condition:

Will succeed because the number 3 will be converted to true. TO false the following values ​​will be given:

  • "" (empty line)
  • 0 (number 0)

So any non-zero number and non-zero string will be converted to true and the condition will be satisfied. The exception is a line consisting of one zero:

It will also be converted to false.

I touched on this topic with reference to boolean in the homework for this lesson. Be sure to complete it. Now let's move on to the next conditional statement.

switch statement

Beyond the design if-else There is one more condition operator. This - switch. This is a very interesting operator that requires memorizing several rules. Let's first see what it looks like in the following example:

At first, this operator may seem quite complicated. However, if you look at it, everything becomes clear. In operand switch some expression is specified. In our case, this is a variable $x, or rather its meaning - 1 .

In curly braces we list the operators case, after which we indicate the value with which the operand value is compared switch. The comparison is not strict, that is, it is as if we were using the == operator. And if the condition is met, then the code specified after the colon is executed. If none of the conditions are met, then the code from the section is executed default, which in general may not exist, and then nothing will be executed. Please note that within each section case, at the end we wrote the operator break. This is done so that after the code is executed, if the condition is met, the conditions will not continue to be checked. That is, if it weren't for break at the end of the section case 1, then after the text is displayed

The number is 1

the comparison condition with 2 , and then the code in the section would be executed default. Don't forget to write break!

Comparing switch with if

In general, this code could also be written using the construction if-elseif-else:

But in the form of a design switch-case The code in this particular case looks simpler. And that's why:

  1. we immediately see what exactly are we comparing?(variable $x) and we understand that in each condition we are comparing exactly this value, and not any other;
  2. It’s easier for the eye to perceive what are we comparing with?– sections case 1, case 2 visually perceived easier, the compared value is more noticeable.

And again about switch

And I haven't said everything about switch- you can write several case-s in a row, then the code will be executed provided that at least one of them is executed. For example:

Agree, this can be convenient.

Okay, let's go over the features of the operator switch, which must always be remembered.

  1. break interrupts a set of conditions, do not forget to specify it;
  2. section default will be executed if none of the conditions are met. It may be completely absent;
  3. some case-s can be written in a row, then the code in the section will be executed if at least one of the conditions is met.

A little practice

Well, do you remember the conditional operators? Let's put it into practice with more real examples.

Even or odd

Here is one example - you need to determine whether a number is even or not. To do this, we need to check that the remainder of division by 2 will be equal 0 . Read more about operators. Let's do that:

Try changing the variable value yourself $x. Cool, yeah? It works!

Module

Let's now learn how to calculate the modulus of a number. If the number is greater than or equal to zero, then you need to output this number itself; if it is less, replace the sign from minus to plus.

= 0) ( echo "Number modulus: " . $x; ) else ( echo "Number modulus: " . -$x; )

Result:

Number module: 2

As we can see, everything worked successfully.

Ternary operator

In addition, PHP has another operator, which is a shortened form of the construct if-else. This is a ternary operator. At the same time he returns different results depending on whether the condition is met or not. In general, its use looks like this:

Condition? result_if_true: result_if_false

Or using the example of the same module location:

= 0 ? $x: -$x; echo "Module: " . $mod;

Result:

Module 2

Cool, yeah? The ternary operator fits in very elegantly when solving such simple problems.

And a little more practice

Conditions can be placed inside each other and in general, what can you not do with them. For example:

0) ( if ($x >= 100) ( echo "The number is greater than or equal to 100"; ) else ( echo "The number is greater than 0 but less than 100"; ) ) else ( echo "The number is less than or equal to 0"; )

Bottom line

Friends, I hope you liked the lesson. If so, I will be glad if you share it on social networks or tell your friends. This is the best support for the project. Thanks to those who do this. If you have any questions or comments, write about it in the comments. And now, let’s all quickly do our homework, there are even more interesting examples with conditions. Bye everyone!

In this article we continue to study PHP basics and get acquainted with another design called SWITCH – CASE. The essence of this construction is to perform a certain action depending on the value that the variable takes. The operation of the SWITCH – CASE construction is similar, but allows you to implement the choice from several options more compactly and clearly.

This short article will consist of two parts. In the first, we will look at the basics of the SWITCH – CASE design and learn how it works. In the second part we will work through the material again, but using an example. As an example, we will use the simplest option, where a message will be displayed depending on what value the variable takes. Thanks to this structure of the article, in my opinion, all the material will be as clear as possible and you can easily understand the whole essence of the SWITCH - CASE design and apply the acquired knowledge in practice.

Syntax SWITCH – CASE. Operating principle of the SWITCH – CASE design

In PHP, the syntax of the SWITCH – CASE construct is as follows:

Switch ($a) /*Start the construction and register the variable that we will check*/ ( case "value 1": /*If the variable takes the value 1*/ action 1 /*Perform action 1*/ break; /*complete execution */ case "value 2": /*If the variable takes the value 2*/ action 2 /*Perform action 2*/ break; /*Finish execution*/ … default: /*If none of the options are suitable*/ action on default /*Perform the default action*/ break; /*End execution of the SWITCH - CASE construct*/ )

As you can see, for clarity, I have provided a short comment for each line. To be brief, in practice the following most often happens. A variable, for example, using the POST method, is passed a specific value. Then, using the SWITCH – CASE construct, the variable is checked. If there is a match, then a specific action is performed and the check is completed. If no value was passed to the variable, the default operation is performed.

As you may have already noticed, everything is very simple and clear. As mentioned above, the SWITCH – CASE construct could be replaced with the IF – ELSE construct, but in this case the code would be much more cumbersome. For clarity, I will give an example of the same code, but implemented using the IF construct.

If ($vibor == "value 1") (action 1) if ($vibor == "value 2") (action 2) ...

SWITCH – CASE design. Usage example

Let us have a website for a company that teaches people programming. The main programming languages ​​are PHP and C++. We need that when ordering training courses, the user selects the programming language he needs and receives a corresponding message. This solution can be implemented using the SWITCH – CASE design.

$vibor = "PHP"; switch ($vibor) ( case "PHP": echo "The programming language has been selected - $vibor. To study it..."; break; case "C++": echo "The programming language has been selected - $vibor. To study it..."; break; case "Other": echo "You can also choose another programming language from the list..."; break; default: echo "You have not chosen which programming language you want to learn."; break; )

In the example above, the $vibor variable was initially already assigned a value. In practice, this value is assigned depending on which option the user selects. The value is then checked using the SWITCH – CASE construct. If similarity is found, then a certain action is performed. In our case, a message with instructions is displayed. If the user has not selected the desired option, the site will display a default message.

In our example, the variable received the value “PHP”. As a result, the user will receive the message “The programming language selected is PHP. To study it...”, after which the execution of the SWITCH – CASE construct is completed and the rest of the document that follows the closing curly brace is executed. As you can see, a variable was used in the message, which will automatically be replaced with its value. You can read about this in the first article about PHP called “”.

This concludes the article. I think I managed to explain the whole essence of the SWITCH - CASE design and no questions should arise. If you are new to the blog and do not want to miss the appearance of other articles, I recommend that you subscribe to blog news in any other way convenient for you in the “” section or use the form below.

That's all. Good luck to you and see you soon on the blog pages

Condition and choice are key constructs of the language. Correct decision making is the basis of a high-quality algorithm and clear, easy-to-understand code. The correct design of the algorithm and the correct use of comments are factors of stability and reliability.

Modern programming is still not without rigidity. Code, once written, can adapt to changing task conditions only with the help of a competent specialist. But still, the level of code mobility is determined by the skill level of its author.

Select construct syntax

The PHP switch case selection construct is very simple to write, correctly executed, and convenient in practice. The example proposes a function that formats text with HTML tags. If the first parameter contains "bold" or "italic", then the function's result wraps the second parameter with "strong" or "i" tags.

The result in the browser displays the contents of the second parameter in bold or italic style. Any other value for the first parameter is interpreted as a color and wraps the second parameter with a "font" tag.

This function does not check the correctness of the initial parameters and can only be used in that part of the code where the parameters cannot go beyond acceptable limits.

In the proposed example, the use of the “break” operator is redundant, since as a result of the fulfillment of any condition, the function will be exited using the “return” operator.

Description of the PHP construct: switch case

The condition being tested is written in parentheses after the "switch" keyword. The body of the structure consists of "case" sections and one block of "default" statements, which is executed only if none of the "case" blocks are triggered.

There is a very significant nuance. A block of "case" statements begins after the ":" character and ends with the "break" statement. The presence of the "break" operator is not necessary. If it is not present, then the next "case" condition will be checked. The conditions are always checked until the first match occurs. Naturally, the conditions here are only "==".

Each "case" section is executed only if the condition is true, but the "default" block of statements will always be executed if there is a missing "break" statement in the "case" section that was triggered, or if none of the conditions matched.

In fact, in PHP: switch case for several values ​​has several blocks of statements. To formally follow the syntax, each block of statements must be terminated with a "break".

As soon as a condition is matched, the corresponding section and, if there is no "break" in it, everything that follows it is executed. In the example, the value of the variable "$x" is 1 and there are no "breaks", so the result = "-one--two--default-".

Nesting of conditionals

The language does not limit the developer in the level of nesting. It is allowed to nest switch cases. PHP also does not limit the programmer in the choice of operators that can be used inside case.

This allows you to create beautiful and easy to read algorithms. For example, you need to recognize the CSS rules table. You can immediately set switch case PHP to recognize classes and identifiers, then recognize the rules themselves. This is an obvious solution, but cumbersome. Both classes and identifiers use similar rules.

It is more convenient to recognize rules using a switch case. You can enable a function in PHP that will access rules recognition. We can go further. Many rules allow similar meanings. Reasoning in this way, try to build the reverse process: switch case in PHP will be executed in the form of functions, the first one works at the value level, the second one at the rule level, and the third one is called from the level of a specific class or identifier.

(PHP 4, PHP 5, PHP 7)

Operator switch is like a series of IF statements with the same condition. In many cases, you may need to compare the same variable (or expression) to many different values, and execute different sections of code depending on what value that variable (or expression) takes. This is exactly the case for which the operator is convenient switch.

Comment: Please note that, unlike some other languages, the continue operator is used in constructs switch and acts like an operator break. If you have a design switch is inside a loop and you need to move to the next iteration of the loop, use continue 2.

Comment:

Note that the switch/case construct uses an imprecise comparison (==).

The following two examples illustrate two different ways to write the same thing. One uses a series of operators if And elseif, and the other is the operator switch:

Example #1 Operator switch

Example #2 Operator switch allows comparison with the string type

It is important to understand how the operator switch is done to avoid errors. Operator switch performs line by line (actually expression by expression). At the beginning, no code is executed. Only if an operator is found case, whose value matches the value of the expression in the operator switch, PHP starts executing statements. PHP continues executing statements until the end of the block switch or until it meets the operator break. If you don't write the statement break at the end of a case section, PHP will continue executing the commands in the next case section. For example:

In this example, if $i is 0, then PHP will execute all echo! If $i is 1, PHP will execute the last two echo statements. You will only get the expected behavior of the operator ('i equals 2' will be displayed) if $i equals 2. So, it is important not to forget about the operators break(even though you may want to avoid its intended use in certain circumstances).

In the operator switch the expression is evaluated once and this result is compared with each statement case. In expression elseif, the expression is evaluated again. If your condition is more complex than a simple comparison and/or is in a loop, the construct switch can work faster.

The list of statements to be executed in a case section can also be empty, which simply transfers control to the list of statements in the next case section.

A special type of case construction is default. Control comes here when none of the other case statements have worked. For example.

(PHP 4, PHP 5, PHP 7)

Operator switch is like a series of IF statements with the same condition. In many cases, you may need to compare the same variable (or expression) to many different values, and execute different sections of code depending on what value that variable (or expression) takes. This is exactly the case for which the operator is convenient switch.

Comment: Note that unlike some other languages, the continue statement is used in switch statements and acts similar to the statement break. If you have a switch statement inside a loop and you need to move to the next iteration of the loop, use continue 2.

Comment:

Note that the swich/case construct uses an imprecise comparison (==) .

The following two examples illustrate two different ways to write the same thing. One uses a series of operators if And elseif, and the other is the operator switch:

Example #1 Operator switch

if ($i == 0 ) (
echo "i is 0" ;
) elseif ($i == 1 ) (
echo "i is 1" ;
) elseif ($i == 2 ) (
echo "i equals 2" ;
}

switch ($i) (
case 0 :
echo "i is 0" ;
break;
case 1 :
echo "i is 1" ;
break;
case 2:
echo "i equals 2" ;
break;
}
?>

Example #2 Operator switch allows comparison with strings

switch ($i) (
case "apple" :
echo "i is an apple" ;
break;
case "chocolate" :
echo "i is a chocolate bar" ;
break;
case "pie" :
echo "i is a pie" ;
break;
}
?>

It is important to understand how the operator switch is done to avoid errors. Operator switch performs line by line (actually expression by expression). At the beginning, no code is executed. Only if an operator is found case, whose value matches the value of the expression in the operator switch, PHP starts executing statements. PHP continues executing statements until the end of the block switch or until it meets the operator break. If you don't write the statement break at the end of a case section, PHP will continue executing the commands in the next case section. For example:

switch ($i) (
case 0 :
echo "i is 0" ;
case 1 :
echo "i is 1" ;
case 2:
echo "i equals 2" ;
}
?>

In this example, if $i is 0, then PHP will execute all echo! If $i is 1, PHP will execute the last two echo statements. You will only get the expected behavior of the operator ("i equals 2" will be displayed) if $i is equal to 2. So, it is important to not forget about the operators break(even though you may want to avoid its intended use under certain circumstances).

In the operator switch the expression is evaluated once and this result is compared with each statement case. In expression elseif, the expression is evaluated again. If your condition is more complex than a simple comparison and/or is in a loop, the construct switch can work faster.

The list of statements to be executed in a case section can also be empty, which simply transfers control to the list of statements in the next case section.

switch ($i) (
case 0 :
case 1 :
case 2:
echo "i is less than 3, but not negative";
break;
case 3:
echo "i is 3" ;
}
?>

A special type of case construction -- default. Control comes here when none of the other case statements have worked. For example:

switch ($i) (
case 0 :
echo "i is 0" ;
break;
case 1 :
echo "i is 1" ;
break;
case 2:
echo "i equals 2" ;
break;
default:
echo
"i is not equal to 0, 1 or 2";
}
?>

Expression in the operator case can be any expression that is cast to a simple type, that is, to an integer type, or to a floating-point type (float), or to a string. Arrays or objects cannot be used here until they are dereferenced to a simple type.