#3.1 IF and ELSE PHP with examples

The conditionals they are the most basic form of control structures. They are a simple but powerful tool that will bring us closer to the realization of complex scripts.

In this tutorial on conditionals I am going to deal with the sentences IF and ELSE with php examples. Specifically, in this tutorial I am going to deal with the following concepts from the php course:

  • Using variables in php
  • Arithmetic operations in php
  • Control structures in programming

Content

  • What are if and else used for?
  • How to use if and else in php
    • The if statement
    • The else statement
  • if and else possibilities
  • Reinforce if and else with exercises

What are if and else used for?

The sentences if and else They allow us, like other control structures, to put an execution condition on certain lines of code, all of them contained as a general rule between braces:

<?php
if ( 1 < 5 ) {
    echo '1 es menor que 5';
}
?>

In this example php I have made an obvious comparison, but I am limiting the use of the statement threw out for the condition (1 < 5) to be met. The sentences if and else make sense when we talk about assumptions, that is, what would happen if… Also, if we translate directly from English, we can see that precisely “if” is a conditional if.

Imagine the chances of the weather tomorrow on a normal spring day, the chances would be rainy, sunny or cloudy. The planning of the following day according to these possibilities would be the equivalence of the conditionals in programming: if it rains tomorrow I will take boots and an umbrella; if it’s sunny tomorrow I’ll wear short sleeves and a light jacket; if tomorrow is cloudy I will carry the umbrella but I will put on shoes.

Let’s now imagine the real example that I have shown you but solving it with a php script. we have a variable $weather which can have the value ‘rain’, ‘sun’ or ‘clouds’ and depending on this we will show one message or another.

<?php
if ( $clima == 'lluvia' ){
     echo 'Llevaré botas y paraguas';
}
if ( $clima == 'sol' ){
    echo 'Llevaré manga corta y chaqueta fina';
}
if ( $clima == 'nubes' ){
    echo 'Cargaré con el paraguas pero me pondré zapatos';
}
?>

He script that you have seen will show the message corresponding to the value that the variable takes $weather. I have covered all the possibilities of the problem, therefore it is a complete solution.

As you can see, the possibilities of using conditionals are enormous, and it is that the use of if and else It will accompany you throughout all your php learning and with all security in your future developments of the majority of programming languages ​​that you touch.

How to use if and else in php

The if statement

Wear if and else It is simple, in the previous point you have seen several examples of use, a sample of how to work with if. Let’s see a more complex example: a script that depending on the value taken by a variable $number Say if this is negative or positive.

<?php
if ( $número < 0 ){
    echo 'El valor de la variable $número es menor que 0';
}
if ( $número > 0 ){
   echo 'El número ' . $número . ' es positivo ';
}
?>

We have conditional on execution of a line of code or several depending on a condition programmed by us. This condition can also be multiple using the statements && (or and), || (or hear).

In the next example they give us a number with the day of the month in numerical format, and according to a range of values ​​we will say if it is the beginning, middle or end of the month:

<?php
if (  $diaMes < 7 ){
     echo 'Estamos a primeros de mes';
}
if ( $diaMes >= 7 && $diaMes <=23 ){
    echo 'Es mediados de mes';
}
if ( $diaMes > 23 ){
    echo 'Es final de mes';
}
?>

In this example I have resolved the first days of the month (from 1 to 6) and the last (from 24 to 31) with if’s of a single condition, while for the interval of days between the two previous conditions I have used &&this indicates that they must be fulfilled both conditions so that the result of these conditions is true.

if instead of && (and) would have put || (either) only one condition should have been met for the result of the set to be true (true in programming).

The else statement

Sentence else is the second part of the binomial if and else.

as well as the sentence if by itself or nesting it gives us the possibility of solving multiple cases always indicating at least one condition that must result in true, the statement else, that you should always go after a if, allows us to condition the execution of a code if the if related does not hold.

Let’s see a solution from the previous example to tell if a number is negative or positive using now if and else:

<?php
if ( $número < 0 ) {
   echo 'El número ' . $número . ' es negativo';
} else {
   echo 'El número ' . $número . ' es positivo';
}
?>

If we read this php example in common language it would be like this: If the number is less than 0 then the number is negative, otherwise the number is positive. He else as its meaning in English is a “but”, so whenever a ifhis else will be true and its content will be executed.

if and else possibilities

The sentences if and else combined or nested will allow us to solve complex problems. For example:

php script that always returns the largest of three numbers $a, $b, $c:

<?php
if ( $a > $b ){
   if ( $a > $c ) {
      echo 'El mayor es ' . $a;
   } else {
      echo 'El mayor es ' . $b;
   }
} else { //$a será mayor que $b
   if ( $b > $c ) {
      echo 'El mayor es ' . $b;
   } else {
      echo 'El myor es ' . $c;
   }
}
?>

In this example I have used if and else To go dividing the possibilities two by two, if it is too complex for you, remember that the trick is to observe the braces of each conditional, ignoring the lines they contain if their condition is not met, or in the case of the else if the condition of the if has been fulfilled.

The result of this code will always be a message indicating which of the numbers is the greatest.

Reinforce if and else with exercises

Remember, mastering these is practice, lots of practice. To finish understanding these statements, I recommend that you carry out a series of php exercises and review their solutions later. Here are exercises and their solutions:

  • if and else exercises for beginners
  • Solutions to if and else exercises for beginners
  • Solutions if and else exercises intermediate level

Leave a Reply