PHP Guide: switch and for,foreach,while

PHP Tutorial: switch statement and for/foreach/while loops

Hello everyone, today we confront the topic switches to iterate over arrays and loops.

Switch

The switch statement is no more than one “alternative” to declare a series of if {} elseif {} elseif {} else {} with some small differences. Let’s look at this example:

$choice = 1;

switch ($choice) {
   case 1:
        echo "You have chosen 1!"
        break;
   case 2:
        echo "You selected 2";
        break;
   case 3:
        echo "You have chosen 3!"
        break;
   default:
        echo "The selected number is neither 1, nor 2, nor 3";
        break;
}

As you can easily guess, the switch statement is especially useful when you expect certain values ​​of a variable and is a good idea to avoid a long if statements like this:

$choice = 1;

if ($choice == 1)
     echo "You have chosen 1!"
elseif ($choice == 2)
     echo "You selected 2";
elseif ($choice == 3)
     echo "You have chosen 3!"
else
     echo "Your choice is neither one, nor two, nor 3";

In fact, if you try to perform these two pieces of code, you will notice that the result is identical. We can therefore say that the switch statement is used to make “visible” in the code and make it more streamlined and easily comprehensible.

The for loop

For those coming from languages ​​like C or Java or Javascript, you probably already know what we’re going to deal with. The for loop is useful when you want to iterate (ie, iterate through the items one by one and perform various operations for each element) an array. Consider the following example:

$array = array ("first", "second","third");
for ($ i = 0; i = $ 2, $ i + +) {
 //... Code to be executed
}

You may notice the three parameters that make up the loop, we’re going to list and describe:

  • $ i = 0; – This means that you assign to a variable value of 0, and will be used as a counter to scroll the list of items (remember that arrays have a pair of key-> value, and the keys you count from 0, not 1)
  • $ i <= 2 – This is a condition, in the literal meaning is to indicate, perform what is the right of this parameter, until $i is equal to 2 (like if)
  • $i++ – This is the condition which is repeated if the previous parameter returns boolean TRUE

Now that we know what the parameters can be set to modify the example above as follows:

$array = array("first", "second","third");
for ($i = 0,$i = 2, $i++) {
    echo $array [$i];
}

This example will print three strings, which means “first”, “second” and “third” because we used the $i to read the values ​​of the array. For testing purpose try to do “echo $ array [0]; echo $ array [1],” and you will see that the result will be identical
Now the question that arises is: what if my array contains an element of “fourth”?
Of course, following the example above the fourth value will not be returned, as the second parameter of the loop, ie: $i=2 will return true when it comes to its “third” (remember that counts from 0). And this is where the count() function comes in help.

$array = array("first", "second","third","fourth");
for ($ i = 0;  $i<= count($array) $i++) {
    echo $array[$i];
}

As I’m sure you noticed, no longer uses the equal sign (=) but was changed to less-or-equal (<=). This is because the feature count(), count the elements of an array but it starts counting at 1 and our array starts counting from 0! To avoid this incompatibility makes use of the symbol-or-less equal so that even if the count reaches 2 our array was counted for all 3 elements.

The foreach

The foreach loop is nothing but a quicker and cleaner way to cycle a given array without using the for loop. Taking the above example you can write:

$array = array ("first","second","third","fourth");
foreach ($array as $key => $val) {
    echo $val;
}

This example will produce the same result as the loop. The first argument of the loop is to iterate the array, the second is a way to assign the variable $key and the index of the current $val the value associated with him. In fact, writing this piece of code:

$array = array ("first","second","third","fourth");
foreach ($array as $key => $val) {
   echo "$key index with value $val";
}

The result will be “index 0 with value first”, “Index value with a second” and so on. Note that the foreach loop, like the if statement can be written in different ways with the same results.
You can write without parentheses when you want to perform a single operation per cycle.

$array = array ("first","second","third","fourth");
foreach ($array as $key => $val)
       echo "$key index with value $val";

You can write with a colon and a endforeach final method is particularly useful when you want to insert loops into HTML

$array = array ("first","second","third","fourth");
foreach ($array as $key => $val):
    echo "$key index with value $val";
endforeach;

The while loop

The while loop is an alternative method to iterate over a Boolean expression and can be represented (as in the for or foreach) as a series of if repeated. Because unlike for foreach or while statement does not give us any kind of parameter to be set to increment the counter of our array, we do it ourselves.

$array = array ("first","second","third","fourth");
$i=0;
while ($i <= count($array)) {
     echo $array[$i];
     $i++;
}

The while loop which means translated from WHEREAS, can be translated into literary terms, “Do this while the value is this.” Obviously the result of this cycle will be identical to a for loop, foreach. Note that while there is a variant of which can be written as follows:

$array = array("first","second","third","fourth");
$i=0;
do {
   echo $ array[$i];
   $i++;
} While ($i <= count($array));

As I’m sure you understand the code in do {} is executed if the parameter provided in while () returns true.

It’s the end of our little tutorial in the next post will talk about how to use the internal functions of PHP to manage strings, search, replace pieces of string and so on.
Thank you for reading this article, see you to next post!