by Dinesh Thakur

This chapter presents two important principles to assimilate: the condititions and loops. This first concept is especially important since it allows to perform a series of actions depending on the conditions being tested. As for the second, it allows to repeat N times a series of actions, and in very short time (at human scale). The advantage of the arrival of the computer is to make life easier for users performing tasks that they can not fulfill. If you ask a person to count from 0 up to 1000, it will take several minutes while a computer will process this transaction in milliseconds (or even a few nanoseconds as its computing power). Then immediately understand the benefits of computing.

Conditional structures

A conditional structure enables whether to run a series of instructions based on an original condition (also referred to as expression or predicate). If the calculation of this condition returns true then the statement block concerned is running. The expressions can be assessed more or less complex, ie they may consist of a combination of comparison operators, and logical operators same functions.

PHP introduced conditional constructs: if, elseif, else and switch.

The conditional statement if ()

The if statement is the simplest and most widely used conditional statementsIt is the best known of all because it is found in all programming languages. It used to run a block of statements only if the expression is true. Its syntax is as follows:

Principle of operation of the if ()

  if (expression)
     {
         instruction block;
     }

If the expression included in the parentheses evaluates to the Boolean value TRUE, the following statement is executed. Otherwise, execution proceeds directly to the next line. Its operation illustrate with a simple example.

Example of using the if ()


<?php
    // Declare a variable
    $speed = 60;

   // One tests the value of the variable
   if ($speed> 50)
      {
          echo 'I lose 1 point for speeding!<br />';
          echo 'The policeman said to me, "Gently roll now!"';
      }
?>

The above code models the speed of a vehicle $speed by a variable. The condition for its checks the speed of the vehicle. If this value exceeds 50(Km/h), while the driver is stopped by police and loses a point on his license. If the speed is less than or equal to 50 then nothing happens because the driver is not in violation.

The else clause

The else clause (if translated), added after the closing brace of the if() block, used to define a set of instructions that will be executed if the expression tested is false (returns FALSE). Returning to our previous example to illustrate its operation.

Using the else clause in our previous example

<?php
    // Declare a variable
    $speed = 40;

    // One tests the value of the variable
    if ($speed> 50)
     {
         echo 'The police m \' stop! <br />';
         echo 'I lose 1 point for speeding!<br />';
         echo 'The policeman said to me, "Gently roll now!"';
      }
     else
      {
         echo 'The police let me follow my path!';
      }
?>

We added the else clause in our code and updated the value of $ variable speed (40 km / h). When executing this code, the condition is not crossed since 40 is not greater than 50 so it enters the else clause is executed, and the only echo () statement.

The elseif () statement

It can be translated as "or". This instruction must up after the closing brace of an if () block. It allows to avoid overlapping of conditional blocks if () and it is possible to combine several. Yet Aggregates our example with this conditional statement.

Example of the elseif conditional statement ()


<?php
     // Declare a variable
     $speed = 82;

     // One tests the value of the variable
     if ($speed>50 && $speed <70)
        {
            echo 'The police man stop! <br />';
            echo 'I lose 1 point for speeding!<br />';
            echo 'The policeman said to me, "Gently roll now!"';
        }
            elseif ($speed> 70 && $speed <80)
               {
                   echo 'The police man stop!<br /> ';
                   echo 'I lose 2 points for speeding echo<br />';
                   echo 'The policeman verbalizes me by a fine';
               }
           elseif ($speed> 80 && $speed <90)
              {
                   echo 'The police man stop!<br />';
                   echo 'I lose 3 points for speeding!<br />';
                   echo 'The policeman verbalizes me a big fine "';
              }
           elseif ($speed> 90)
             {
                   echo 'The police stop! <br />';
                   echo 'I lose 4 points for speeding!<br />';
                   echo 'The policeman removed my license!<br />';
                   echo 'I finally walk!';
             }
          else
            {
                  echo 'The police let me follow my path!';
             }
?>

In this example, we simulate the loss of points on the driving license according to the speed. The speed limit is always 50 Km/h. We drive 82 km/h or 32 km/h over the speed limit. We will enter the second elseif statement block () because 82 is between 80 and 89 (90 excluded). We then lose 3 points on our license and we also recovered a fine to pay.

On the interpretation perspective, PHP will test one by one the conditions. If the first is false, it moves to the second. If the second is false, it moves to the third and so on. If it meets a real, between inside and then it executes the block of instructions. If none are true, he finally executed the statement block of the else clause.

Alternative syntax on one line

Note: in case we have only one instruction to execute a conditional statement, we can do without braces. So we write for example:

Example of using the instruction writes one line

<?php
    // Declare a variable
    $speed = 82;
    // One tests the value of the variable
    if ($speed> 50 && $speed <70)
        echo 'I lose 1 point for speeding!';
    elseif ($speed> 70 && $speed <80)
        echo 'I lose 2 points for speeding echo';
    elseif ($speed> 80 && $speed <90)
       echo 'I lose 3 points for speeding!';
    elseif ($speed> 90)
       echo 'I lose 4 points for speeding!';
    else
       echo 'I make flashing headlights drivers!';
?>

Nevertheless, we recommend you always use the braces that make easier reading of the code.

The switch statement ()

There is another alternative to the if () / elseif () / else or to the nesting blocks if (). It is called switch () (lead in case). This conditional statement allows you to test all the possible values ‚Äč‚Äčthat can take a variable. Here is its syntax.

Syntax switch conditional statement ()

switch (expression)
{
    value1 box:
        instructions;
    break;

    value2 box:
       instructions;
    break;

   default:
      instructions;
   break;
}

To illustrate its use with another example. The above is not suitable. We'll modeled a video game. The player must choose a character.

Example of use of the conditional statement switch ()

<?php
    // Player has choosen his character ('Elf')
    $character = 'elf';

    // Test the value of the character
    switch ($character)
        {
            case 'sorcerer':
                 echo 'You have choosen the sorcerer!';
                 echo 'You have magical powers.';
            break;

            case 'warrior':
                 echo 'You have choosen the warrior!';
                 echo 'You have\'s knives. ';
            break;

           case 'king':
                echo 'You choose the king!';
                echo 'You live in a castle surrounded by guards.';
           break;

          case 'elf':
               echo 'You choose\'s elf! ';
               echo 'You can fly and move quickly.';
          break;

         case 'ogre':
             echo 'You have choosen the ogre ';
             echo 'You have plenty of arm strength.';
         break;

        default:
            echo 'Please select your character!';
        break;
     }
?>

If the variable has an undefined value in the switch(), then launches a default block of instructions. The case keyword sets the value to be tested. This value follows this keyword. The keyword break, meanwhile, exits the switch () block is executed if a block of instructions. It is optional but highly recommended in most use cases.

It is also recommended to always include a default block to ensure that we have a default action if the value of the variable is not referenced in the switch (). This could save you many surprises.