Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

IF, SWITCH, FOR, WHILE and FOREACH in PHP

In this article, we will learn the IF, SWITCH, FOR, WHILE and FOREACH operators in the PHP language.

One of the first and most important concepts that we learn when we study programming is that the control structures. As the name itself suggests, they are structures used to strategically modify the behavior of the application in a certain point, thus ensuring decisions to be made and, based on these, a code snippet be executed.

These structures are divided in two groups: conditional and loop. The conditional structures are used to evaluate a certain condition and, according to the result, execute a specific routine.

Loops, on the other hand, perform a code snippet repeatedly based on the result of the evaluation of a previously established condition.

Despite the concept being the same, or very similar for all languages, the syntax varies from case to case. Therefore, besides the general theoretical definition, you must know the functioning syntax of each operator in the language you want to use.

IF

The IF operator is used to evaluate a boolean condition, that is, which may assume only two distinct values: TRUE or FALSE. IF means PROVIDED in Portuguese and the structure works in the following manner: IF (condition) THEN (do something). However, the THEN is not used in the PHP, being enough to use the IF, according to the model in Listing 1:

Listing 1: Basic Syntax for the use of the IF

if(condition)
{
	//code
}

The keys are used to delimit a code block, in case only one line needed to be executed, the keys could be removed. However, it is safer to use them, for you never know when you will need to insert another line to the code.

The IF operator may be complemented with the ELSE operator, which means OTHERWISE. That is, IF a condition is satisfied, then do something. OTHERWISE, do something other.

The ELSE only needs to be used when there is something specific to be done if the condition is not satisfied. The syntax of use is demonstrated in Listing 2.

Listing 2: IF-ELSE syntax of use

if(condition)
{
	//code 1
}
else
{	
//code 2
}

In case there are various specific conditions to be validated, other IFs may be inserted after the ELSE, according to Listing 3.

Listing 3: IF-ELSE IF syntax of use

if(condition1)
{	
	//code 1
}
else if(condition2)
{
	//code 2
}
else
{
	//code 3
}

In the code above, if condition 1 was not satisfied, the second condition would be analyzed. If neither of the first two was valid, the code of teh ELSE block would be executed.

The following Listing shows an example of the use of the complete IF operator practice.

Listing 4: IF use example

if($hour <= 12)
echo “It's morning”;
else if($hour > 12 && $hour <= 18)
	echo “It's evening”;
else
	echo “It's night”; 

In the Listing above, some analysis are made of the value of the variable $hour, which, in theory, stores the current time. Depending on its value, a specific message is displayed.

SWITCH

Roughly speaking, we can say that the SWITCH works as the union of several IFs, however, in a more compact and organized fashion. Imagine, for example, a situation in which a value inserted by the user needs to be read. This value, in its turn, may assume five values. It would be necessary to write five successive IFs in order to evaluate all the possibilities. Let us see what that would be like in practice.

Listing 5: Verification of various possibilities with IF

if($option == 1)
	//code 1
else if($option == 2)
	//code 2
else if($option == 3)
	//code 3
else if($option == 4)
	//code 4
else if($option == 5)
	//code 5
else
	//none of the options 

This code could be sufficiently reduced using the SWITCH operator which evaluates an expression based on several predetermined values. If the expression doesn't have any of the valid values, a standard value may be defined. Below, we have the basic syntax of such structure.

Listing 6: Basic syntax of the SWITCH

switch(expression)
{
case value1:
//code 1
break;
case value2:
//code 2
break;
default:
//default code
break;
}

As you can see, in one single block, various possibilities are evaluated. The break command is necessary at the end of each code block (which doesn't need to be surrounded by keys) in order for the other options to be discarded, in case one of them is fulfilled.

The example above could be rewritten in the following manner:

Listing 7: Verification of various possibilities with SWITCH

switch($option)
{
case 1:
//code 1
break;
case 2:
//code 2
break;
case 3:
//code 3
break;
case 4:
//code 4
break;
case 5:
//code 5
break;
default:
//none of the options
break;
}

WHILE

As for the WHILE, it fits in the loops structures. This operator is used to execute a block of codes several times, for as long as a determined condition is fulfilled. In other words, this structure works in the following way: AS LONG AS (a condition is satisfied), DO SOMETHING. Where DO SOMETHING may be one or various PHP commands.

The basic use syntax of this structure is displayed below.

Listing 8: WHILE basic syntax

while(condition)
{
	//commands
}

In this case, the evaluated condition must also be boolean, and may assume the values true or false.

Listing 9 displays a practical example of the use of the operator WHILE.

Listing 9: Example of the use of the WHILE

var $counter = 0;
while($counter < 10)
{
echo $counter;
$counter++;
}

In this example, we have a variable "counter" which value is evaluated and, as long as it is less than ten, a code is executed, printing this value and adding a unit to it.

After the execution of the block of commands, the value of the expression is again evaluated and, if it is valid, the codes are again executed.

FOR

The loop structure FOR is used to execute a set o commands for a determined amount of times. For this operator, an initial situation, a condition and an action to be executed at each repetition are supplied.

Generally, we inform a variable which functions as a repetition counter, with its value, a condition to be in attendance to so that each repetition is executed and an increase to the counter.

Observing the syntax that follows, it is easier to understand the operation.

Listing 10: Syntax of the FOR operator

for(initial value; condition; increase)
{
	//commands
}

In Listing 11, a practical example is displayed to smoothen the understanding of this structure.

Listing 11: Example of use of the FOR

for($counter = 0; $counter < 10; $counter++)
{
	//commands
}

The code above may be understood as "with the counter starting at zero and, as long as this value is less than ten, execute the commands and increase one unit in its value".

In practice, this code has the same function than that of Listing 9.

FOREACH

The FOREACH is a simplification of the FOR operator to work in data collections, that is, vectors and matrixes. It allows access to each element individually, repeating over the whole collection and without the need for index information.

For example, supposing it was necessary to explore a vector with some elements with the FOR. It would be necessary to use a counter to serve, also, as an index to access each element, as shown in the following Listing.

Listing 12: Repetition in a vector with the FOR

$vector = array(1, 2, 3, 4, 5);
for($i = 0; $i < 5; $i++)
{
	$item = $vector[$i];
echo $item;
}

This code could be simplified with the usage of the FOREACH operator, of which the syntax is displayed below.

Listing 13: Syntax of the FOREACH operator

foreach(vector as variable)
{
	//variable represents an element of the vector at each loop
}

Thus, rewriting the code in Listing 12, we would have:

Listing 14: Example of the usage of the FOREACH

$vector = array(1, 2, 3, 4, 5);
foreach($vector as $item)
{
echo $item;
}

In this manner, at each loop (repetition), the variable $item represents an element of the vector.

Conclusion

As we have seen in this article, it is essential to any programmer to know the syntax and functioning of the control structures, in theory and in practice, since they are used in applications on a daily basis.

I hope that the content presented here may be useful for those who are initiating their studies on the PHP language.

Hope you liked and see you next time.



Front-end developer, WebEditor of MrBool.com and SEO Analyst. Work in the development area for over 4 years. For freelance work visit my portfolio: www.ricardoarrigoni.com.br

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login