Chat in Telegram

Conditions in PHP

02.11.2022 at 07:49
29
+1

Hi! Here comes another PHP lesson. Today's topic is one of the most favorite among those who are starting to program. Still, because the conditions in PHP are what allows us to compose various algorithms. Depending on the conditions, 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 you can use to implement conditions. All of them are used, and have their advantages in different situations, or, if you like, conditions. There are only conditions around, right? So. After all, 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 this.

As you should remember from the last lesson, in PHP, depending on the operator, the operands are cast to a certain type. Conditional operators in PHP follow the same rules, and here the operand is always cast to a boolean value. If this value is true, then we consider that the condition is met, and if it is false, then the condition is not met. Depending on whether the condition is met, we can do or not do any actions. And here I propose to consider the first conditional statement - if.

"if" statement

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

<?php

if (condition) {
    the code to be executed if the condition is met;
}

And in real life, the use of the if statement looks like this:

<?php

if (true) {
    echo 'Condition met';
}

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

<?php

$x = 15;

if ($x > 10) {
    echo 'Number 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, another code is executed? Yes, you certainly may! To do this, use the else statement along with the if statement. It is written after the curly braces that enclose the code that is executed when the condition is met. And the structure looks like this:

<?php

$x = 15;

if ($x > 10) {
    echo 'Number greater than 10';
} else {
    echo 'Number 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 at the very beginning we assign the value 8 to the variable $x, then a message will be displayed:

Number less than or equal to 10

Try it right now.

"if-elseif-else" construct: multiple conditions

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

<?php

$x = 10;

if ($x > 10) {
    echo 'Number greater than 10';
} elseif ($x == 10) {
    echo 'Number equal to 10';
}

In this case, the screen will display:

Number equal to 10

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

<?php

$x = 9;

if ($x > 10) {
    echo 'Number greater than 10';
} elseif ($x == 10) {
    echo 'Number equal to 10';
} else {
    echo 'Number less than 10';
}

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

<?php

$x = 3;

if ($x <= 0) {
    echo 'Number less than or equal to 0';
} elseif ($x == 1) {
    echo 'The number is 1';
} elseif ($x == 2) {
    echo 'The number is 2';
} else {
    echo 'The number did not match any of the conditions';
}

Cast to boolean

Remember, in the lesson about data types in PHP, we learned how to explicitly cast values to any type. For example:

<?php

$x = (boolean)3;

var_dump($x);

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

<?php

if (3) {
    echo 'Condition met';
}

It will succeed because the number 3 will be converted to true.
The following values will be cast to false:

  • '' (empty string)
  • 0 (number 0)
  • [] (empty array)

Thus, any non-zero number and non-zero string will be converted to true and the condition will be met. The exception is a string consisting of one zero:

'0'

It will also be converted to false.

I covered this topic with casting to boolean in the homework assignment for this tutorial. Be sure to complete it. Now let's move on to the next conditional statement.

"switch" statement

In addition to the if-else construct, there is one more conditional operator. This is switch. This is a very interesting operator that requires memorization of several rules. Let's first see what it looks like in the following example:

<?php

$x = 1;

switch ($x) {
    case 1:
        echo 'Number is 1';
        break;
    case 2:
        echo 'Number is 2';
        break;
    default:
        echo 'Number is neither 1 nor 2';
}

At first glance, this operator may seem rather complicated. However, if you understand, then everything becomes clear. An expression is specified in the switch operand. In our case, this is the $x variable, or rather its value is 1.

In curly braces, we enumerate case statements, after which we indicate the value with which the value of the switch operand is compared. The comparison is not strict, that 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 is met, then the code from the default section is executed, which, in general, may not exist, and then nothing will be executed. Please note that inside each case section, at the end, we have written a break statement. This is done so that after the code is executed, if the condition is met, the condition check does not continue. That is, if there was no break at the end of the case 1 section, then after the text

The number is 1

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

switch vs if

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

<?php

$x = 1;

if ($x == 1) {
    echo 'Number is 1';
} elseif ($x == 2) {
    echo 'Number is 2';
} else {
    echo 'Number is neither 1 nor 2';
}

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

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

And again about switch

And I haven’t said everything about switch yet - 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:

<?php

$x = 2;

switch ($x) {
    case 1:
    case 2:
        echo 'Number is 1 or 2';
        break;
    case 5:
        echo 'Number is 5';
        break;
    default:
        echo 'Number is neither 1 nor 2 nor 5';
}

Agree, it can be convenient.

Okay, let's go over the features of the switch statement that you should always keep in mind.

  1. break breaks a set of conditions, do not forget to specify it;
  2. default section will be executed if none of the conditions are met. It may be completely absent;
  3. several _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, 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 after dividing by 2 will be 0. Read more about operators here. Let's do that:

<?php

$x = 2;

if ($x % 2 == 0) {
    echo 'The number is even';
} else {
    echo 'The number is odd';
}

Try changing the value of the $x variable yourself. Cool, yeah? It is working!

The absolute value of a number

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 print this number itself, if it is less, change the sign from minus to plus.

<?php

$x = -2;

if ($x >= 0) {
     echo 'Absolute value: ' . $x;
} else {
     echo 'Absolute value: ' . -$x;
}

Result:

Absolute value: 2

As we can see, everything worked out successfully.

Ternary operator

In addition, PHP has another operator, which is a shortened form of the if-else construct. This is a ternary operator. However, it returns different results depending on whether the condition is met or not. In general, its use is as follows:

condition ? result_if_true : result_if_false

Or using the same example of finding the absolute value of a number:

<?php

$x = -2;

$mod = $x >= 0 ? $x : -$x;

echo 'Abs: ' . $mod;

Result:

Abs: 2

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

And some more practice

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

<?php

$x = 105;

if ($x > 0) {
    if ($x >= 100) {
        echo 'Number is greater than or equal to 100';
    } else {
        echo 'Number greater than 0 but less than 100';
    }
} else {
    echo 'Number less than or equal to 0';
}

What is the result

Friends, I hope you enjoyed 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 it. If you have any questions or comments - write about it in the comments. And now - we are all quickly doing our homework, there are even more interesting examples with conditions. Bye everyone!

loader
02.11.2022 at 07:49
29
+1
Homework

Try the following conditions:

  • if ('string') {echo 'Condition met';}
  • if (0) {echo 'Condition met';}
  • if (null) {echo 'Condition met';}
  • if (5) {echo 'Condition met';}

Explain the result.

Use the ternary operator to determine if a number is even or odd and print the result.

Comments
New comment