facebook google plus twitter
Webucator's Free PHP Tutorial

Lesson: Flow Control

Welcome to our free PHP tutorial. This tutorial is based on Webucator's Introduction to PHP Training course.

In this lesson you will learn about flow control in PHP with if-elseif-else conditions and with loops.

Lesson Goals

  • Work with if-elseif-else conditions in PHP.
  • Work with switch/case statements in PHP.
  • Work with loops in PHP.

Conditional Processing

Conditional processing allows programmers to output different code based on specific conditions. There are two conditional structures in PHP - if-elseif-else and switch/case.

If Conditions

Simple if statement

Syntax

if (conditions)
	Do this;

In the above code, the Do this; statement will either run or not run depending on whether or not the conditions are true. This syntax can only be used when the condition affects a single line of code. For a block of code, use the following syntax.

Syntax

if (conditions)
{
	Do this;
	Then do this;
	And this too;
}

The lines of code affected by the if condition are put in a code block, which is surrounded by curly brackets to indicate that all of the code either should or should not be executed, depending on the result of the if condition.

if-else statement

Syntax

if (conditions)
{
	Do this;
}
else
{
	Do that;
}

if-elseif-else statement

Syntax

if (conditions)
{
	Do this;
}
elseif (other conditions)
{
	Do that;
}
else
{
	Do this other thing;
}

The two syntax blocks above show an if-else and an if-elseif-else statement, which can have any number of elseif blocks.

The following table shows PHP's comparison operators.

Comparison Operators
Operator Description
== Equals
!= Doesn't equal
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to
=== Identical (same value and same type)
!== Not Identical

The following example demonstrates an if-elseif-else statement.

Code Sample:

FlowControl/Demos/If.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>if-elseif-else</title>
</head>
<body>
<?php
$age = 21;
if ($age >= 21) 
{
	echo 'You can vote and drink!';
} 
elseif ($age >= 18)
{
	echo 'You can vote, but can\'t drink.';
} 
else 
{
	echo 'You cannot vote or drink.';
}
?>
</body>
</html>

The file is relatively simple. You can see the different results by changing the value of $age.

Compound If Statements

More complex if statements often require that several conditions be checked. The table below shows and and or operators for checking multiple conditions and the not operator for negating a boolean value (i.e, turning true to false or vice versa).

Logical Operators
Operator Name Example
&& AND $a && $b
|| OR $a || $b
! NOT !$b

The following example shows these logical operators in practice.

Code Sample:

FlowControl/Demos/If2.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>if-elseif-else</title>
</head>
<body>
<?php
$age = 21;
$citizen = false;
if ($age >= 21 && !$citizen) 
{
	echo 'You can drink, but can\'t vote.';
} 
elseif ($age >= 21) 
{
	echo 'You can vote and drink!';
} 
elseif ($age >= 18 && $citizen)
{
	echo 'You can vote, but can\'t drink.';
} 
else 
{
	echo 'You cannot vote or drink.';
}
?>
</body>
</html>

switch/case

A switch/case statement is similar to an if statement, except that it can only check for an equality comparison of a single expression. It cannot, for example, be used to check if one value is higher than another.

Syntax

switch (expression)
{
	case 'a' :
		echo 'expression is a';
		break;
	case 'b' :
		echo 'expression is b';
		break;
	case 'c' :
		echo 'expression is c';
		break;
	default :
		echo 'expression is unknown';
		break;
}

The break statement is important. Without it, after a single match is found, all following statements will execute.

The following example demonstrates a switch/case statement without break statements.

Code Sample:

FlowControl/Demos/Switch.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>switch/case</title>
</head>
<body>
<?php
$quantity = 1;
switch ($quantity)
{
	case 1 :
		echo 'Quantity is 1';
	case 2 :
		echo 'Quantity is 2';
	default :
		echo 'Quantity is not 1 or 2';
}
?>
</body>
</html>

The screenshot below shows the result.Switch Without Break

Notice that, once a match is found, all remaining echo statements are output. The following example shows how this can be fixed by adding break statements.

Code Sample:

FlowControl/Demos/SwitchWithBreak.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>switch/case</title>
</head>
<body>
<?php
$quantity = 1;
switch ($quantity)
{
	case 1 :
		echo 'Quantity is 1';
		break;
	case 2 :
		echo 'Quantity is 2';
		break;
	default :
		echo 'Quantity is not 1 or 2';
}
?>
</body>
</html>

This time, only the first statement is output:First Statement

Working with Conditions

Duration: 20 to 30 minutes.

In this exercise, you will create a page for handling a simple form submission.

  1. Open FlowControl/Exercises/Greeting.html in your editor and review the code. This is the form that will be submitted. Filled out, it looks like this:Greeting Form This form is submitted using the get method, which means the form entries will be appended to the query string and will be accessible in the $_GET array.
    HTML forms will be discussed more later in the course.
  2. Open FlowControl/Exercises/Greeting.php in your editor.
  3. Insert a PHP block that checks to see if the user filled out both the LastName and the Gender fields in the form.
    • If the user failed to fill out either one of the fields, write out an error message to the screen.
    • If the user filled out both fields, return a gender-appropriate greeting such as "Hello Mr. Dunn!" or "Hello Ms. Dunn!" If the gender is not recognizable (e.g, not male or female), return an error message.
  4. Try to use both an if condition and a switch statement in this exercise.
  5. When you are done, test your solution in your browser.

Challenge

It is likely that your solution does not take into account different cases for the gender. For example, "MALE" and "FEMALE" may not be recognized as valid genders. Try to find the function at http://www.php.net that can be used for converting the user's entry to all lowercase letters and use that function to make the gender check case insensitive.

Solution:

FlowControl/Solutions/Greeting.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting Page</title>
</head>
<body>
<?php
	$lastName = $_GET['LastName'];
	$gender = $_GET['Gender'];
	
	if ($lastName == '' || $gender == '')
	{
		echo 'Error: You must fill out the form.
				Please <a href="Greeting.html">try again</a>.';
	}
	else
	{
		switch($gender)
		{
			case 'male' :
				echo "Hello Mr. $lastName!";
				break;
			case 'female' :
				echo "Hello Ms. $lastName!";
				break;
			default :
				echo "<b>$gender</b> is not a gender!";
		}
	}
?>
</body>
</html>

Challenge Solution:

FlowControl/Solutions/Greeting-challenge.php
---- C O D E   O M I T T E D ----

		switch(strtolower($gender))
		{
			case 'male' :
				echo "Hello Mr. $lastName!";
				break;
			case 'female' :
				echo "Hello Ms. $lastName!";
				break;
			default :
				echo "<b>$gender</b> is not a gender!";
		}
---- C O D E   O M I T T E D ----

Loops

As the name implies, loops are used to loop (or iterate) over code blocks. The following section shows the syntax for different types of loops. Each loop will return "12345".

There are several types of loops in PHP.

  • while
  • do...while
  • for
  • foreach

    foreach loops will be covered in the Arrays lesson.

while

while loops are used to execute a block of code repeatedly while one or more conditions is true.

Syntax

$a=1;
while ($a < 6)
{
	echo $a;
	$a++;
}

do...while

do...while loops are used to execute a block of code repeatedly until one or more conditions is found to be false. The difference between while loops and do...while loops is that the condition is checked after the code block is executed. This means that, in a do...while loop, the code block will always be executed at least once.

Syntax

$a=1;
do
{
	echo $a;
	$a++;
}
while ($a < 6);

for

A for loop takes three expressions separated by semi-colons and grouped in parentheses before the block to be iterated through.

  1. The first expression is executed once before the loop starts. It is usually used to initialize the conditions.
  2. The second expression is evaluated before each iteration through the loop. If it evaluates to false, the loop ends.
  3. The third expression is executed at the end of each iteration through the loop. It is usually used to make changes that can affect the second expression.

Syntax

for ($a=1; $a < 6; $a++)
{
	echo $a;
}

break and continue

To break out of a loop, insert a break statement.

Syntax

for ($a=1; $a < 6; $a++)
{
	echo $a;
	if ($a > 3)
	{
		break;
	}
}

To jump to the next iteration of a loop without executing the remaining statements in the block, insert a continue statement.

Syntax

for ($a=1; $a < 6; $a++)
{
	if ($a == 3)
	{
		continue;
	}
	echo $a;
}

Working with Loops

Duration: 10 to 15 minutes.
  1. Open FlowControl/Exercises/Loops.php in your editor.
  2. Under the while header, use a while loop to output all the even numbers that are less than or equal to 100.
  3. Under the for header, use a for loop to output all the odd numbers that are less than or equal to 100.

Challenge

In both loops, skip all numbers that are divisible by 3. Be careful not to get caught in an infinite loop.

Solution:

FlowControl/Solutions/Loops.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Loops</title>
</head>

<body>
<h2>while</h2>
<ul>
<?php
	$a=2;
	while ($a <= 100)
	{
		echo "<li>$a</li>";
		$a+=2;
	}
?>
</ul>

<h2>for</h2>
<ul>
<?php
	for ($a=1; $a <= 100; $a+=2)
	{
		echo "<li>$a</li>";
	}
?>
</ul>
</body>
</html>

Challenge Solution:

FlowControl/Solutions/Loops-challenge.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Loops</title>
</head>

<body>
<h2>while</h2>
<ul>
<?php
	$a=2;
	while ($a <= 100)
	{
		if ($a % 3 == 0)
		{
			$a+=2;
			continue;
		}
		echo "<li>$a</li>";
		$a+=2;
	}
?>
</ul>

<h2>for</h2>
<ul>
<?php
	for ($a=1; $a <= 100; $a+=2)
	{
		if ($a % 3 == 0)
		{
			continue;
		}
		echo "<li>$a</li>";
	}
?>
</ul>
</body>
</html>