Categories
PHP

Control Structures in PHP

Objectives

  • To learn to use conditional test statements to compare numerical and string data values
  • To learn to use looping statements to repeat statements
  • To learn to use Boolean operators to create compound conditional test statements

Using Conditional Test Statements

Conditional statements provide a way for scripts to test for certain data values and then to react differently depending on the value found.

Using the if Statement

Use an if statement to specify a test condition and a set of statements to run when a test condition is true.

if ($average > 69)
    $Grade="Pass";
print "Grade=$Grade ";
print "Your average was $average";

If $average was equal to 70 then the above would output:

Grad=Pass Your average was 70

Boolean Expressions

Boolean expressions use Boolean operators to compare values and output is a Boolean value (true or false).

PHP Boolean Operators

Test Operator Effect
== Equal to
!= Notequal to
< Lessthan
> Greater than
>= Greater thanor equal to
<= Lessthan or equal to

The === and !=== test for equality and inequality, additionally testing for data type. So '1'==1 is true whereas '1'===1 is false. and '1'!=1 is false and '1'!==1 is true.

A Full Example

Consider the following application which receives two grades as input and determines whether their average is above 89. It uses an HTML form for input grades:

Enter First Score <input type="text" size="4" maxlength="7" name="grade1">
Enter Second Score <input type="text" size="4" maxlength="7" name="grade2">

And the receiving inline PHP:

<html>
<head><title>Decisions</title></head>
<body>
<?php
$grade1= $_POST["grade1"];//get the first grade
$grade2= $_POST["grade2"];//gest the second grade
$average = ($grade1 + $grade2) / 2;
if ( $average > 89 ) {
   print "Average score: $average You got an A! <br>";
}
$max=$grade1;
if ($grade1 < $grade2) {
   $max = $grade2;
}
print ("Your max score was $max");
?>
</body></html>

Comparing Strings

PHP represents strings using character encodings such as the ASCII code values. These encodings provide a standard, numerical way to represent characters in computer storage. Every letter, number, and symbol is translated into a code number.

For instance:

  • “A” is ASCII code 65, “B” is 66, “C” is 67, and so on and “a” is ASCII code 97, “b” is 98, “c” is 99, and so on.
  • ASCII “A” is less than ASCII “a,” “B” is less than “b,” and “c” is less than “d”.

Comparing Strings

You can use == operator to check if one string is equal to another. For example,

$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 == $sport2) {
   print ("$sport1 is equal to $sport2." );
} else {
   print ("$sport1 is not equal to $sport2.");
}

Outputs: Hockey is not equal to Soccer.

Also use <, >, <=, and >= operators to compare string values using ASCII code values. For Example

$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 < $sport2) {
print ("$sport1 is less than $sport2.");
} else {
print ("$sport1 is not less than $sport2.");
}

Outputs Hockey is less than Soccer.

A Full Example …

Consider the following HTML form element that sets the elements “first” and “second” of $_POST

<form action="" method="POST">
First Name: <input type="text" name="first">
Second Name: <input type="text" name="second">
</form>

Consider the receiving code as follows:

<html>
<head>
<title>String Comparison Results</title>
</head>
<body>
<?php
$first = $_POST["first"];
$second = $_POST["second"];
print ("First=$first Second=$second<br>");
if ($first == $second) {
   print ("$first and $second are equal");
}elseif ($first < $second) {
   print ("$first is less than $second");
}else{ //if ($first > $second)
   print ("$first is greater than $second");
}
?>
</body></html>

This code will compare strings and state that the first is equal, less than, or greater than the second.

Above, since we wanted to code more than 2 branches in our application, we used if and else for the first and last and elseif for all others in between.

if (Boolean expression 1) {
   //one or more PHP statements
} elseif (Boolean expression 2) {
   //one or more PHP statements
} elseif (Boolean expression 3) {
   //one or more PHP statements
} elseif (Boolean expression 4) {
   //one or more PHP statements
}else {
   //one or more PHP statements
}

In the above, each Boolean expression will only be evaluated if all preceding Boolean expressions evaluate to false. Furthermore, the branch which will run is the first one from the top for which the Boolean expression evaluates to true. If and only if all Boolean expressions evaluate to false, the else branch will be run.

Notice the ordering of the clauses in the following example.

$opening = 9;
$lunchstart=12;
$lunchend=13;
$closing=17;
if ($hour < $opening) {
   echo "Sorry, it is $hour and we open at $opening.";
} elseif ($hour < $lunchstart) {
   echo "Good morning. It is $hour. ";
   echo "We can help you until $closing, except ";
   echo "lunch, from $lunchstart to $lunchend.";
} elseif ($hour < $lunchend) {
   echo "Sorry, we are out to lunch until $lunchend. ";
   echo "We close for the day at $closing";
} elseif ($hour < $closing) {
   echo "Good afternoon. The time is $hour. ";
   echo "Here to help you until $closing";
} else { //if ($hour <= 23) {
   echo 'Sorry, we have gone home already. ';
   echo "We will be back tomorrow at $opening";
} 

Use an else clause with if and possibly one or more elseif clauses. This is to specify the statements to run when all the previous Boolean expressions evaluate to false.

Switch Statement

Use switch statements to run code depending on a set of discrete values, i.e., specific values as opposed to ranges of values.

switch ($rating) {
   case 1:
      $rated = "Poor";
      print "The rating was $rated";
      break;
   case 2:
      $rated = "Fair";
      print "The rating was $rated";
      break;
   case 3:
      $rated = "Good";
      print "The rating was $rated";
      break;
   default:
      print "Error: that rating does not exist";
}

In the above code, the value of $rating is accessed. If it is 1, the branch labeled case 1: will be run. In general, if the value is x, if there is a label case x:, then this will be the starting point to run code within the switch block. All case blocks are ended with a break statement, otherwise, the PHP interpreter will continue running code from the following case block.

Repetition

Scripts can use loop statements to repeat sections of code. This allows us to write more flexible scripts.

Using a for loop

Use a for loop to repeat a set of statements a specific number of times.

for ( $i = 0; $i < $max; $i++ ) {//The initialization
//Set of statements to repeat
}

Full Script Example

<html>
<head><title>Loops</title></head>
<body>
<font size="5" color="blue"> Generate Square and Cube Values</font><br>
<form action=“somewhere.php" method="post">
<?php
  print ("Select Start Number");
  print ("<select name=\"start\">");
  for ($i=0; $i<10; $i++) {
    print ("<option>$i</option>");
  }
  print ("</select>"); 
  print ("<br>Select End Number");
  print ("<select name=\"end\">");
  for ($i=10; $i<20; $i++){
    print "(<option>$i</option>)";
  } 
  print ("</select>"); 
?><br>
<input type="submit" value="Submit">
<input type="reset" value="Clear and Restart"> 
</form>
</body>
</html>

Using the foreach loop

When we try to access elements of a collection, such as an array, the foreach loop is easier to use than the for loop. The syntax is as follows:

foreach($collection as $item){
  //perform an action on $item
}

When the collection is a dictionary, a collection of key/value pairs, the syntax is slightly different:

foreach($collection as $key => $value){
  //perform actions on $key and $value
  //the data should be organized such that
  //$collection[$key] == $value
}

Using the while loop

Use the while loop to repeat a set of statements as long as a Boolean expression remains true.

while ($ctr < $max) {
  //Set of statements to repeat
}

A while loop will repeat as long as the Boolean expression is true. If the expression initially evaluates to false, then the statements within the loop body will never run.

In order to avoid infinite looping, the statements in the while loop must lead to modifying the value of the boolean expression. In the example above, the value of $ctr must increase to eventually be greater than or equal to $max.

If the loop conditional test always true, then the loop will never end. This is an infinite loop. This would consume resources on the Web server and possibly slow down other server activity.

A Full Script Example

<html>
<head><title>While Loop</title></head>
<body>
<font size="4" color="blue"> Table of Square and Cube Values </font>
<table border=1>
<tr> <th> Numb </th> <th> Sqr </th> <th> Cubed </th> </tr>
<?php
$start = $_POST["start"]; $end = $_POST["end"];
$i = $start;
while ($i <= $end) {
$sqr=$i*$i;
$cubed=$sqr*$i;
print ("<tr><td>$i</td><td>$sqr</td><td>$cubed</td></tr>");
$i = $i + 1;
}
?></table></body></html>

TIP Using Either the while loop or the for loop for Some Problems

For some loops you can use either the while loop or the for loop. For example, the following two loops both output “i=0 i=1 i=2 i=3 i=4”.

for( $i=0; $i<5; $i++ ){
  print "i=$i ";
}
$i = 0; 
while($i < 5 ){
  print "i=$i ";
  $i=$i + 1;
}

Using Boolean Operators

PHP supports a set of Boolean operators you can use to create compound Boolean expressions. These may be used within an if statement or a while statement to specify more than one condition. For example, consider the following

while ($x > $max && $found != 1) {...}

Boolean Operators

PHP supports three logical test operators.

1. &&—the AND operator. Example:

while ($ctr < $max && $flag == 0) {

Whenever either of these expressions is false, the loop will terminate.

2. ||—the OR operator. Example:

if ($ctr != $max || $flag == 0) {...}

Carries out the statements within the if statement, if either $ctr is not equal to $max or $flag, is equal to 0.

3. !—the NOT operator. Used to test whether an

expression is false. Example,

if (!$flag == 0) {...}

This statement is true when $flag is anything except 0.

The following example asks the user to guess a “secret” two-digit combination and uses Boolean operators. The Input HTML form uses the following to set pick1. A similar group sets a variable pick2.

…<font size=4> Pick a number from 1 to 9<br />
<?php
for($i=1;$i<=9;$i++)
  print("<input type="radio" name="pick1" value='$i'>$i");
print("<br />Pick a second number<br />");
for($i=1;$i<=9;$i++)
  print("<input type="radio" name="pick2" value='$i'>$i");
?></font>

A Full Script Example

<html>
<head><title>Number Guess Results </title><head>
<body>
<?php
$pick1 =$_POST["pick1"];
$pick2 =$_POST["pick2"];
$combo1=5;
$combo2=6;
if (($pick1 == $combo1) && ($pick2 == $combo2)) {
  print ("Congratulations you got both secret numbers $combo1 $combo2!");
} elseif (($pick1 == $combo1) || ($pick2 == $combo2)){
  print ("You got one number right.");
} else {
  print ("Sorry, you are totally wrong!");
}
print ("You guessed $pick1 and $pick2.");
?>
</body>
</html>

The ternary operator

The ternary operator evaluates one expression if the condition is true and another if the condition is false.

(condition?if true:if false);

It is normally used in assignment and sometimes directly for return/output values, e.g.,

$max=($a>=$b?$a:$b);
print('The max is ' . ($a>=$b?$a:$b));
return ($a>=$b?$a:$b);

Summary

Use conditional statements to test for certain conditions and, based on the results of the test, to run specific script statements.

Loops expand the types of programming problems that you can solve and allow you to solve some programming problems much more concisely.

Use Boolean AND (&&), OR (||) and NOT (!) operators to build compound Boolean expressions.

By Michel

My name is Michel Paquette. I currently teach my students how to create data-driven Web applications at Vanier College, in Montreal.

My GitHub page contains a few examples of Web applications. Also consult my YouTube channels: @CSTutoringDotCa and @MichelPaquette.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.