3. Control Statements – The PHP Workshop

3. Control Statements

Overview

By the end of this chapter, you will be able to describe Boolean expressions; leverage logical operators to compose Boolean expressions; choose the right comparison operators within a control statement; describe branching and different looping techniques in PHP; apply branching with ifelse, switch case, break, and continue statements; differentiate between bounded and unbounded loops; implement loops such as while, dowhile, for, and foreach; and write a PHP script to create a movie listing application.

Introduction

Since PHP is a dynamically typed language where types are associated with data instead of variables, it's essential to understand the role that types play in the data operations landscape. In the previous chapter, we learned about the available data types in PHP, their usage with variables and typecasting. We also practiced adding and removing items from an array and went through type conversion and alternative approaches to assigning string data to a variable with heredoc and nowdoc.

In this chapter, we will discuss control statements and why they are essential, and we'll explore what PHP has to offer in this area. Control statements are the most important feature of any programming language. In simple terms, they help to control the flow of a program. Branching and looping are the main types of control structures that help to decide program flow. They also help to craft recursive loops for complex program flows.

Branching allows us to follow the correct path among multiple conditions based on a certain logic. For example, say that we want to make contact with a person. The person might have an email address or a cell number and we might want to either email or SMS the person. A branching structure will help us to determine whether there is an email address associated with that contact information and email the person based on that logic. And if an email address is not available, then we can opt for an alternative communication approach, such as SMS.

The logic that helps branching can be composed of one or more conditions; for example, checking whether the email address is available and checking whether the email address is valid. Normally, each branch of code groups a set of statements to execute; for example, if the email address is available, then email the contact, log the email delivery in the history, update the sender that the email has been sent successfully, and so on. PHP supports if…else and switch control statements for branching. The idea of branching is all about deciding on and executing the correct plan:

Figure 3.1: Branching diagram

Looping allows us to perform repetitive tasks or execute program statements repetitively as long as a certain logic has been fulfilled. For example, we need to send emails to all the persons in a given list who have a valid email address. The looping structure allows us to iterate through the list of persons and send them emails one by one – if the given email addresses are valid, the loop will continue until the end of the list. while, do…while, for, and foreach are the different looping techniques available in PHP:

Figure 3.2: Looping diagram

Boolean Expressions

Branching and looping structures evaluate the logic to execute a branch or execute a loop. That logic could test a certain value, could be a comparison of values, or could test a logical relationship, and it can be written as an expression. The expression is evaluated as a Boolean value; that is, true or false by the branching and looping structures. For branching, the expression serves as an entry check for that branch so that we can decide whether to choose that branch of code or not. For looping, the expression might serve as an entry or exit check for that loop so that we can decide how many times the loop should iterate. For example, to email a list of persons, we can write an expression to determine the size of the list so that we set how many times we do the emailing task and write another expression that checks the email address validity to send the email.

A Boolean expression is an expression that produces a result of either true or false. A Boolean expression can consist of Boolean constants, Boolean data in variables, logical and comparison expressions, and even other types of expressions that yield a Boolean true or false. A Boolean expression uses the logical operators not, and, and or to check the truthiness or untruthiness or the falseness of any statement. Consider a fruit analogy: "I love apples". The expression is true if apple is a fruit. What about "I love both apples and oranges"? The expression is true if both "I love apples" and "I love oranges" are true. Comparison operators also play a role in a Boolean expression when we need to compare two values to identify whether they are equal, or one is greater or less than the other. Comparison is not only limited to values but also extends into data types.

In the next section, we will discuss Boolean constants and learn how to write a Boolean expression using operators, and, throughout the chapter, we will apply logical expression evaluations as a Boolean value.

Note

All the examples in this chapter follow the styling recommendations in the PSR standards coding style guide, which is available at https://packt.live/2VtVsUZ.

Boolean Constants

true and false are the only two Boolean values treated as constants. A simple Boolean value can be a simple expression like the following:

if (true) {

    echo "I love programming.";

} else {

    echo "I hate programming.";

}

If the statement within parentheses results in true, then the true block should be executed; otherwise, the false block should.

Alternatively, we could write the following expression:

if (false) {

    echo "I hate programming.";

} else {

    echo "I love programming.";

}

Both approaches output I love programming..

In the preceding examples, we used the if…else control statement, which we are going to discuss a little later in this chapter.

Logical Operators

Logical Operators combine Boolean values and result in a new Boolean value. In a Boolean expression, to represent relational logic, we use such operators. There are four of them: not, and, or (the famous notandor trio) and xor (the exclusive or). Consider a fruit analogy again: "I love fruits, except apples." The expression is true if the fruit is not an apple. Hence, to negate a statement, we use the not operator. What about "I love either apples or oranges"? The expression is true if either of the "I love apples" or "I love oranges" statements is true. Hence, we use or to result in boolean true if any condition is true and we use and when both conditions need to be true.

Logical operators can be used to compose multiple expressions into one complex expression. For example, the statement "I love either apples or oranges but not watermelon" can be broken into smaller statements, such as "I love apples," or "I love oranges," and "I don't love watermelon." The expression is true if the fruit is not watermelon and if either of the statements "I love apples" or "I love oranges" is true.

The not Operator

The not operator is used to apply negation to a statement. The following code outputs true if the variable value is not true:

!$a

The and Operator

The and operator is used to conjunct multiple variables or expressions to produce a new Boolean value – true or false:

$a and $b

$a && $b

The preceding code outputs true if both $a and $b variables are true.

Note

There are two different variations of the and operator here and they work on a different order of precedence.

The order in which an operation is performed first in an expression is decided by the precedence. The precedence of the and operator is lower than that of the && operator.

The or Operator

The or operator is used to conjunct multiple variables or expressions to produce a new Boolean value – true or false:

$a or $b

$a || $b

The preceding code outputs true if either variable $a or $b is true.

Note

There are two different variations of the or operator here and they work on a different order of precedence.

The xor Operator

The xor operator is used to conjunct multiple variables or expressions to produce a new Boolean value – true or false:

$a xor $b

The preceding code outputs true if $a or $b is not true at once. Consider a fruit analogy again: the statement "I love mango or lemons but not both" is false when both "I love mango" and "I love lemons" are true at the same time.

Note

In PHP, there are two different variations of and and or which operate in a different order of precedence. See the operator precedence table at https://packt.live/2IFwFYR.

Short-Circuit Evaluation and Operator Precedence

Short-circuit evaluation is known as a minimal evaluation of Boolean operators, where the second condition won't be evaluated if the first condition is sufficient enough to determine the value of the expression for the PHP interpreter. It is fundamental to know that if the first condition of the and operation is false, then the overall evaluation must produce false and you don't necessarily need to evaluate the second condition. The same goes for the or operator: if the first condition is true, then the overall evaluation must produce true, no matter if the second condition is false.

Short-circuit evaluation will do the minimum number of comparisons possible to evaluate conditions. Here are some examples of short circuit logical operators:

function foo() {

    return true;

}

$a = (false && foo());

$b = (false and foo());

The preceding foo() function will never be called as the first part of the expression gives the logical conclusion. As with and, if the first argument is false, you don't need to evaluate the rest as the and operation is false if at least one argument is false:

function foo() {

    return false;

}

$a = (true  || foo());

$b = (true  or  foo());

The foo() function will never get called as the first part of the expression gives the logical conclusion. As with or, if the first argument is true, you don't need to evaluate the rest as the or operation is true if at least one argument is true.

To look at another example, short-circuit evaluation is useful for conditions like the following:

if ($todayIsSunday && $isNotRaining) {

    echo "Let's play UNO at my place.";

}

If $todayIsSunday is false, then the whole expression is evaluated as false and there is no chance of playing games at home.

Note

The evaluation of logical expressions ceases once the result is known.

The Precedence of Logical Operators

We need to be aware of the precedence of the same logical operators in an assignment statement so that the Boolean values don't run into the assignment before evaluating the result. The following examples show you how the precedence of the same logical operator (|| / or) might ruin the evaluation.

|| versus or

Consider the following example:

$a = false || true; //outputs true

The result of the (false || true) expression has been assigned to $a and evaluated like ($a=(false||true)) since || has higher precedence than =:

$a = false or true; //outputs false!

The false constant is assigned to $a before the or operation and evaluates like (($a = false) or true) since or has lower precedence than =.

&& versus and

Consider the following example:

$a = true && false; //outputs false

The result of the (true && false) expression has been assigned to $a and evaluated like ($a = (true && false)) since && has a higher priority than =:

$a = true and false; //outputs true!

The true constant has been assigned to $a before the and operation occurs and evaluated like (($a = true) and false) since and has a lower priority than =.

Consider the following use case, where we need to grant access if the user has both a username and password. In the example, we can see that the user doesn't have a password, so access should not be granted:

$hasUsername = true;

$hasPassword = false;

$access = $hasUsername and $hasPassword; //true

Here, since $hasPassword is false, $access should not be granted or should be false. Instead, $access becomes true as the statement evaluated like (($access = $hasUsername) and $hasPassword) and the user is granted access without a password.

Therefore, to avoid such a bad evaluation of an expression, it is recommended practice to use parentheses to evaluate expressions as a unit within the parentheses.

Note

and and or have lower precedence than = but || and && have higher priority.

Comparison Operators

We often need to compare values to decide the program flow. For example, we may want to ride in a four-seater car and we need to make sure that the number of passengers doesn't exceed the car's capacity. So, in programming, to examine such conditions, we often utilize comparison operators.

Comparison operators compare two values and return true or false based on the given comparison. A comparison involves checking whether two values are equal or not equal, equal and of the same data type or not, less than, greater than, and so on. Alternatively, you can have mixed comparisons such as less than or equal to, greater than or equal to, and so on.

PHP introduces a whole new type of comparison operator – the spaceship operator, <=>, which checks the equality of two numbers and allows us to know which number is the greater of the two.

Let's check out the comparison operators and their behaviors:

Figure 3.3: Operators and their descriptions

Note

Type conversion takes place when we compare two different types of values, such as an integer and a string. The string will be converted to a number for numeric comparison; that is, 1 == "01" is equivalent to 1 == 1. For === and !==, which compares the type along with the value, type conversion is not applicable.

For various type comparisons, see Comparison with various types, which is available at https://packt.live/2Vsk4NZ.

Check out some interesting examples of comparison operators:

Figure 3.4: Table of comparison operators

With the preceding different types of examples, hopefully, we should have a clear picture of comparison operators and behind-the-scenes type juggling.

Note

During the evaluation of expressions, the precedence of comparison operators is higher than Boolean operators.

For example, in this multiple expression, ($smallNumber > 2 && $smallNumber < 5), the comparisons are performed before the Boolean operation.

Branching

As we discussed earlier, determining the correct path or choosing one block of code to execute among multiple blocks of code can be described as Branching. Branching can be performed based on whether a Boolean expression evaluates to true or false. Hence, following this concept, we get to choose our desired statement or groups of statements to execute based on an outcome of a Boolean expression.

The if and switch statements are the two main branching control structures. if is the most commonly used conditional structure within any programming language. switch can be used in certain situations where multiple branches can be chosen by a single value or expression, or where a series of if statements would be inconvenient.

The if Statement

The syntax of if is as follows:

if (expression)

    statement;

Here, if (expression) is the control structure, and statement is a single-line statement terminated with a semicolon or multiple statements enclosed in a pair of curly braces, like the following:

if (expression) {

    statement1;

        .

        .

     statementN;

}

So, if the result of the expression evaluates to true, the next statement or block of statements should be executed.

Let's look at an example:

$number1 = 5;

$number2 = 3;

if ($number1 > $number2) {

    print("$number1 is greater than $number2"); //prints 5 is greater than 3

}

The preceding expression produces Boolean true so it executes the true branch.

Note

A control structure body might contain a single statement, an enclosed block of statements, or another conditional structure.

The if…else Statement

With the if control structure evaluated as true, we can execute the block of statements that immediately follow, but what if the evaluation produces false within the control expression? We can add an optional else block to execute the statements in it.

Let's see the syntax of the if…else statement:

if (expression)

    statement;

else

    statement;

Here, else is the fallback if the condition is false. With the else block, we can execute statements based on a conditional expression evaluation of false:

Figure 3.5: The if…else statement

Let's look at another example of the if..else control structure:

$number1 = 3;

$number2 = 5;

if ($number1 > $number2) {

    print("$number1 is greater than $ number2");

} else {

    print("$number1 is less than $number2"); //prints 3 is less than 5

}

Now that we have seen the basic implementation of the if and if…else statements, let's create a few basic scripts in the next two exercises to implement them and observe how branching occurs in actual programs.

Exercise 3.1: Creating a Basic Script to Implement the if...else Test Case

In the following exercise, you will learn to acquire the day using PHP's built-in date() function. You will be using an if...else test case to check whether today is Sunday, and then print Get rest or Get ready and go to the office:

  1. Create a PHP file named test-sunday.php and insert the following content:

    <?php

    if ("Sunday" === date("l")) {

            echo "Get rest";

    } else {

            echo "Get ready and go to the office";

    }

    Here, we have used a built-in date function with a date format flag, l (lowercase L), which returns a textual representation of the current day of the week; that is, Sunday through Saturday. Note that uppercase is used for the first character in the day string; that is, Sunday since the function returns that way.

    The if conditional expression, ("Sunday" === date("l")), matches the returned day name with "Sunday". If today is Sunday, then ("Sunday" === "Sunday") identically matches and yields true and prints "Get rest"; otherwise, it prints "Get ready and go to the office".

  2. Run the PHP file from a Terminal or console, like the following command:

    php test-sunday.php

    The script prints Get rest if today is Sunday; otherwise, it prints Get ready and go to the office.

Figure 3.6: The if…else script output

Note

You can find more information about the PHP date function at https://packt.live/35mGNzC.

Exercise 3.2: Implementing the Nested if...else Structure

In the following exercise, we will practice using a nested if...else structure with a different sort of expression within the control statement. We will create a script that will print the difference between two given numbers based on the fact that one number is greater than the other one and the numbers are not equal. Here, both numbers are positive integers.

With the help of a nested if...else structure, we will be testing whether the numbers are equal or not. If they're not equal, then we'll determine which number is greater and subtract the other number from it to print the difference:

  1. Create a PHP file named test-difference.php.
  2. Declare two variables, $a and $b, and assign them values of 5 and 3 respectively, like the following:

    <?php

    $a = 5;

    $b = 3;

  3. Insert an if…else structure, like the following content:

    <?php

    $a = 5;

    $b = 3;

    if($a - $b) {

        //placeholder for inner if...else

    } else {

        print("The numbers are equal");

    }

    As we already know, the result of the expression ID evaluates to true or false, and for a non-Boolean result should be typecast to Boolean. The example expression ($a - $b) depends on the fact that 0 is considered as false, so if the difference is zero, then the expression will be evaluated as false, hence "The numbers are equal" will be printed.

  4. Add another if…else structure inside the if case body to deal with numbers with a difference, like the following:

    <?php

    $a = 5;

    $b = 3;

    if($a - $b) {

        if ($a > $b) {

            $difference = $a - $b;

    } else {

            $difference = $b - $a;

    }

    print("The difference is $difference");

    } else {

        print("The numbers are equal");

    }

  5. In the preceding example, the inner if...else determines which number is greater and subtracts the other from it to print the difference.
  6. Run the PHP file from a Terminal or console with the following command:

    php test-difference.php

    The script prints "The difference is 2" if the numbers are not equal; otherwise, it prints "The numbers are equal" as there is no difference:

    Figure 3.7: The nested if…else script output

  7. Tweak the values of $a and $b and rerun the script for different results.
  8. Our goal is to achieve different conditional coverage, developing the if…else control structure. The if...else construct executes the true branch with the condition evaluated as true; otherwise, it executes the false branch.

The Ternary Operator

The ternary operator can be considered as a shorthand if..else statement with the following syntax:

(expression1)? (expression2): (expression3)

Here, if expression1 evaluates to true, expression2 should be executed; otherwise, expression3 executes a false evaluation of expression1.

Ternary operators can be used for assigning default values, like the following:

$msg = ("Sunday" === date("l"))? "Get rest" : "Get ready and go to the office";

echo $msg;

In the preceding example, if today is Sunday, then it will print "Get rest"; otherwise, it will print Get ready and go to the office, and we can evaluate the condition to return a value on a single line. Ternary operators are suitable for some cases, especially assigning default values, being used in a return statement to evaluate and return a value, or being used in between a dynamic string to parse and print the output.

It is also possible to write a ternary operator in the following way:

echo ($msg) ? :"Get ready and go to the office";

//equivalent to

echo ($msg) ? $msg : "Get ready and go to the office";

This will print the value of the $msg variable if it is not empty; otherwise, it will print "Get ready and go to the office".

The if…elseif…else Statement

Consider an example where you need to evaluate a set of conditions. Say, you want to display a letter grade for an exam based on a range of GPA numbers (out of 4 points); that is, 3.80 to 4 gets grade A+, 3.75 to below 3.80 gets grade A, and so on. So, we need to start from the top condition if the GPA is greater or equal to 3.80, then we can define the GPA as A+; otherwise, if the GPA is greater than or equal to 3.75, then it's an A grade as we have already fallen back from the top condition. If the GPA is greater than or equal to 3.50, then the grade would be A-, and so on.

Consider an article publishing application, where we need to allocate different actions based on the type of user role. Say, if the user is an editor, then the user can create, read, edit, publish, and delete articles. If the user is an author, they can only create, read, and edit articles. If the user is a reader, they can only read and comment on articles, and so on.

Therefore, we might want to evaluate a set of expressions like in the preceding example in order to cover more scenarios. This is where a cascading sequence of expressions should be evaluated, like the following nested if…elseif…else statement syntax:

if (expression1)

    statement;

elseif (expression2)

    statement;

else

    statement;

This if…elseif…else syntax is just the same as the if…else if…else statement, as in the following:

if (expression1)

    statement;

else

    if (expression2)

        statement;

    else

        statement;

Here, more expressions can be evaluated by cascading the if...else statement.

With such a control structure, we can evaluate whether a number is positive, negative, or zero. Check out the following simple example:

if ($n > 0) {

    print("$n is a positive number.");

} elseif ($n) {

    print("$n is a negative number.");

} else {

    print("$n is zero.");

}

Here, we have tried to determine the characteristics of an integer number in $n and we have covered three simple scenarios; that is, checking whether the number is positive, checking whether the number is negative, and finally, we can fall back to the decision that the number is zero. You can add more expressions to be evaluated with elseif statements like this. The structure of the if…else statement supports multiple branching and allows you to execute only a single branch of statements that has a successful Boolean evaluation.

Exercise 3.3: Creating a Script Using the if... elseif... else Statement

In the following exercise, you will learn how to utilize the if...elseif...else control structure to determine an age range. We will create a script that has a variable named $age with a number representing the age. If the age value is equal to or greater than 18, then print "young"; otherwise, if the age value is less than 18 and greater than 10, print "teenager". If the age is less than 10, then print "child".

We will determine the age range from the value given in the $age variable and print the age category accordingly:

  1. Create a PHP file named test-age.php.
  2. Declare the $age variable as in the following:

    <?php

    $age = 12;

  3. Insert the following if…elseif…else structure:

    <?php

    $age = 12;

    if ($age >= 18) {

            print("Young");

    } elseif ($age > 10) {

            print("Teenager");

    } else {

            print("Child");

    }

    Here, we have used comparison operators, which were discussed in previous sections. The ($age >= 18) statement determines whether the age is greater than or equal to 18. If the age is neither greater nor equal to 18, then the execution falls to the next test expression, ($age > 10) to check whether the age is greater than 10 as the age is already less than 18. Again, if the ($age > 10) expression doesn't return true, the age will be considered to be less than 10, hence, categorized as "Child".

  4. Run the PHP file from a Terminal or console, as in the following command:

    php test-age.php

    The script prints "Young", "Teenager", and "Child" based on different age ranges:

    Figure 3.8: The if…elseif…else script output

  5. You might also want to add more test expressions to cover another age range, as in the following:

    <?php

    $age = 12;

    if ($age > 25) {

            print("Adult");

    } elseif ($age >= 18) {

            print("Young");

    } elseif ($age > 10) {

            print("Teenager");

    } else {

            print("Child");

    }

    Here, we have added ($age > 25) as another test expression to show the cascaded if…else structure.

    Note

    The tested age ranges and printed age categories are just for a learning demo.

The switch Case

A switch statement provides multiway branching so that we can choose one among several blocks of code to be executed. It can be considered to be just like multiple if statements on the same expression and having a default block like the final else statement.

According to the yielded value of the expression, the proper case with an appropriate value is picked for execution. The expression can be any kind of expression or a variable that gives a value such as a number or a string:

Figure 3.9: A switch diagram

The syntax of the switch case is as follows:

switch(expression) {

    case value-1:

        statement-1

        statement-2

        ...

        break;

    case value-2:

        statement-3

        statement-4

        ...

        break;     

        ...   

    default:

        default-statement

}

This is what is happening in the preceding code:

  • switch(…){…} is the control structure.
  • expression is the expression that produces a value to be matched in the different cases.
  • case value:… is the block of statements to be executed. In order to execute the block, the case value should be similar to the expression's yielded value.
  • default: is the default block of statements to be executed if the switch expression's yielded value doesn't match any cases, just like else.

    Note

    A switch case does a loose comparison. A loose comparison means it won't check the type. The value evaluated from a switch expression should be equal to the matching case value without checking the type. Say, the switch expression evaluated to number 1 can be matched or is equal to the case values, such as string "1", float 1.00, or Boolean true.

Here is an example switch statement:

<?php

switch ($fruit) {

    case "cherry":

        echo "The fruit is cherry.";

        break;

    case "banana":

        echo "The fruit is banana.";

        break;

    case "avocado":

        echo "The fruit is avocado.";

        break;

    default:

        echo "The fruit cannot be identified.";

        break;

}

The preceding switch statement executes the $fruit expression, which is a variable with a value in it, so the value should be matched with the case values and the corresponding case statements should be executed until the break; statement occurs.

We need to be careful with switch statement usage and the use of break;. Just as in the following example, PHP will continue executing the statements without a break:

<?php

switch ($n) {

    case 0:

        echo "the number is 0 ";

    case 1:

        echo "the number is 1 ";

    case 2:

        echo "the number is 2 ";

}

?>

For $n is 0, the preceding example will print "the number is 0 the number is 1 the number is 2". For $n is 1, it will output "the number is 1 the number is 2", so we need to add a break; statement at the end of each case. We will discuss the break; statement in our next section.

In a switch statement, the given condition is evaluated to match the resultant value with the value of each case.

Also, multiple cases within the same block of statements can be written as follows:

<?php

switch ($n) {

    case 0:

    case 1:

    case 2:

        echo "the number is less than 3.";

        break;

    case 3:

        echo "the number is 3.";

        break;

}

?>

With a default case, we can extend the preceding example as follows:

<?php

switch ($n) {

    case 0:

    case 1:

    case 2:

        echo "the number is less then 3.";

        break;

     case 3:

        echo "the number equals to 3.";

        break;

     default:

        echo "the number is not within 0 to 3.";

}

?>

Note

The switch cases support alternative syntax for a control structure. For more information, check out https://packt.live/2M0IMli.

Now, we will detect data types with a switch case in order to print the data types in an exercise.

Exercise 3.4: Creating a Script to Implement a Switch Case

In the following exercise, we will create a script that will get the type of a variable using the built-in gettype() function in a switch test case and print custom messages for different data types.

For the integer and double data types, we will print "The data type is Number.". Print "The data type is Boolean", "The data type is String", and "The data type is Array" for the boolean, string, and array types, respectively. Also, print "The data type is unknown" for unknown data types and the rest of the data types:

  1. Create a PHP file named test-datatype.php.
  2. Declare the $data variable like the following:

    <?php

    $data = 2.50;

    Here, we have declared a variable that contains a numeric value of type double. We could have added other types of data as well.

  3. So, in order to get the type of the $data variable and match the appropriate case, let's insert the following switch structure:

    <?php

    $data = 2.50;

    switch (gettype($data)) {

            case 'integer':

            case 'double':

                    echo "The data type is Number.";

                    break;

            case 'boolean':

                    echo "The data type is Boolean.";

                    break;

            case 'string':

                    echo "The data type is String.";

                    break;

            case 'array':

                    echo "The data type is Array.";

                    break;

            default:

                    echo "The data type unknown.";

                    break;

    }

    Here, we have used the built-in gettype() function, which returns the type of $data, such as "boolean", "integer", "double", "string", "array", "object", "resource", "NULL", and "unknown type".

    We already know that to execute the same statements for multiple cases, we can combine the cases. For "integer" and "double" strings returned by the switch expression, since the requirement is to print the same message for both, as the type is a number, we kept both cases together. Also, for other data types, we have dealt with matching case statements, and the rest of the types, and even unknown types, have been addressed by the default case.

  4. Run the PHP file from a Terminal or console with the following command:

    php test-datatype.php

    The script prints different messages for different data types:

    Figure 3.10: The switch case output

  5. Tweak the value of $data with different types of data and rerun the script for different outputs.

Looping

A loop is a block of statements written once but executed several times. The code within a loop or the body of a loop is executed a finite number of times, determined by whether certain conditions are met or they may be infinite!

In this chapter, we will be discussing for, foreach, while, and do…while loops with their structures and examples.

Bounded Loops versus Unbounded Loops

A bounded loop has a loop iteration limit and hence executes till that boundary is met. To restrict it to that finite number of iterations, the number of iterations is easily visible in the loop condition or in loop statements and the language constructs assure that it won't loop beyond that.

Again, an unbounded loop iterates until a certain condition is met and the condition can be controlled from inside the loop. Bounded loops are also called count-controlled loops as you can control the iteration count with the help of language constructs; similarly, unbounded loops are condition-controlled loops.

In PHP, while, do…while, and for are all unbounded loops and, regardless of the loop control portion (entry controlled or exit controlled), they are almost the same. We will look at examples of these looping techniques and their application in different use cases.

The while Loop

The while loop is one of the simplest looping constructs. The syntax is as follows:

while (expression)

    statement

// to accommodate multiple statements,

// enclose them by the curly braces

while (expression) {

    statement 1

    statement 2

    …    

}

Here, while (expression) {…} is the control structure that checks the possibility of executing the loop in the expression condition, followed by a single statement, or multiple statements can be enclosed in by a pair of curly braces:

Figure 3.11: A while loop diagram

In a while loop, the condition expression is evaluated as a Boolean. For the first iteration, the expression should be evaluated to true in order to execute the statement(s). Then, it checks for the condition again to proceed with the next iteration. If the condition produces false, the loop terminates without proceeding further.

For example, the following loop will never be executed:

while (false)

    echo "This will never be printed.";

Again, the following loop might execute forever:

while (true)

    echo "This will be printed. " . PHP_EOL;

Here, PHP_EOL holds the end of line character, and was used at the end of the string to print the next string on a new line.

You can set how many times a loop will iterate with a given condition, as in the following loop, which executes exactly seven times:

$count = 1;

while ($count <= 7) {

    echo "This will be printed. " . PHP_EOL;

    $count++;

}

Here, $count starts with value 1 and gets incremented by 1 with the $count++ statement. The loop will print 7 lines, and at iteration number 8, the $count will contain 8, so the ($count <= 7) condition becomes false, and printing is terminated. So, with the count control, we can bound the while loop to execute a certain number of times.

Note

The condition was evaluated at the beginning of the loop; that's why the while loop is an entry-controlled loop.

Exercise 3.5: Printing the Numbers 1 to 10 Using a while Loop

In this exercise, we will simply iterate through a while loop to print numbers 1 through 10 and will apply a condition expression to check the numbers are within a range of 1 to 10 as we will be incrementing the number by 1:

  1. Create a PHP file named print-numbers-while.php.
  2. Declare a $number variable and initialize it to 1.
  3. Insert a while loop to print numbers 1 to 10:

    <?php

    $number = 1;

    while ($number <= 10) {

            echo $number . " ";

            $number++;

    }

    Here, we have initialized the number as 1 in the $number variable. With the ($number <= 10) condition expression, we can guarantee that the loop will not execute or it will not print if the number is greater than 10.

    At the end, we produced the next number by incrementing the $number++; variable. Here, we used an empty string, " ", as a number separator.

    So, Boolean expressions allow us to write test cases with limits or boundaries. Plus, a looping technique can execute a set of statements within those limits or boundaries.

  4. Run the PHP file from a Terminal or console with the following command:

    php print-numbers-while.php

    The script prints 1 through 10:

    Figure 3.12: The while loop output

  5. Tweak the script with different conditional expressions and rerun it to see the new outputs.

The do…while Loop

In contrast with the while loop, the do…while loop comes with the expression evaluation at the end. This means that the loop will iterate through once to execute the code within the loop before the condition is ever evaluated.

The syntax of such an exit-controlled loop is as follows:

do statement

    while (expression);

// to accommodate multiple statements,

// enclose them by the curly braces

do {

    statement 1

    statement 2

    …     

} while (expression);

Here, do {…} while (expression) is the control structure and the expression is the conditional expression, which gives a Boolean result:

Figure 3.13: The do…while loop diagram

For example, the following loop will be executed once regardless of whether the condition evaluates to false:

do

    echo "This will be printed once. " . PHP_EOL;

while (false);

Here, the first iteration of the do...while loop will execute as the expression evaluation comes at the end. If the condition is true, then the second iteration takes place; otherwise, with false, it prevents further looping.

So, we can make use of while or do...while looping based on the fact that one is entry controlled and the other is an exit controlled loop.

You can see how many times a loop can iterate with an end condition. The following loop executes exactly seven times:

$count = 1;

do {

    echo "This will be printed. " . PHP_EOL;

    $count++;

} while ($count <= 7);

Here, $count starts with value 1 and gets incremented by 1 with the $count++ statement. The loop will print 7 lines and at iteration number 7, the $count will contain 8, so the ($count <= 7) condition becomes false, hence, further printing is terminated. So, with the count control, we can bound the do…while loop to execute a certain number of times.

Exercise 3.6: Converting a while Loop to a do...while Loop

In this exercise, we will tweak the previous exercise, replace while with a do…while loop, and rerun the statements to see the outputs:

  1. Open the print-numbers-while.php file and copy the contents into a new file named print-numbers-do-while.php.
  2. Replace the while loop with do...while:

    <?php

    $number = 1;

    do {

        echo $number . " ";

        $number++;

    } while ($number <= 10);

    Here, we have replaced the previous while loop with a do...while control structure.

    The difference with the previous looping technique is that condition testing has been placed at the end of the structure as do...while is an exit controlled loop. The loop should execute at least once regardless of the condition. If the end expression evaluates to true, we proceed with the next iteration. All looping techniques use a conditional expression to check the eligibility of the next iteration in order to guarantee finite looping.

  3. Run the PHP file from a Terminal or console with the following command:

    php print-numbers-do-while.php

    The script prints 1 through 10 with the replaced do...while loop:

    Figure 3.14: The do…while loop output

  4. Tweak the script with different conditional expressions and rerun the script to see the new outputs.

The for Loop

In previous sections, we discussed while and do…while loop structures and saw the way they iterate based on entry and exit conditions. We also looked at the use of a counter or a number initiated from 0 or 1 that gets incremented in each iteration using the post-increment ++ operator and checked that the counter or number doesn't exceed the limit. In practice, while and do…while loops use a loop step value declared before the loop and the step value incremented or decremented inside the loop. This loop step value is used to check the limit of the loop condition. Hence, we need to arrange our way of controlling loop iterations in the case of while and do…while.

To observe such common practice, the for loop can be used, with the structure itself providing expressions for initiating the loop step variable, the step value checking condition, and the step increment/decrement statement.

Let's check out the syntax of a for loop:

for (expression1; expression2; expression3)

    statement

// to accommodate multiple statements,

// enclose them by the curly braces

for (expression1; expression2; expression3) {

    statement1;

    statement2;

    …

}

Here, for (expression1; expression2; expression3) {…} is the control structure and expression2 is the conditional expression evaluated as a Boolean.

The first expression, expression1, is an unconditional expression that is evaluated at the very start of the loop and is considered as a loop initiation statement. Prior to each iteration, expression2 is evaluated as a Boolean expression to true. The loop body executes in each round. expression3 is evaluated at the end of each iteration.

Note

The empty expression2 means the loop will run infinitely.

Working of the for loop can be represented as follows:

Figure 3.15: A for loop diagram

The following example prints numbers 1 through 10:

for ($index = 1; $index <= 10; $index++) {

    echo "$index \n";

}

The preceding for loop executes 10 times and prints 1 through 10. Here, the $index variable is initiated to 1 in the first expression. The second expression checks whether the value of $index is less than or equal to 10 so that the loop iteration can be limited to 10 times, and $index++ increments the value of $index by 1 after each iteration.

The preceding example is similar to the following:

$index = 1;

for (;;) {

    if($index > 10) {

        break;

    }

    echo "$index \n";

    $index++;

}

You can terminate the loop execution with a break statement, preventing further execution within the block.

Note that an empty for loop can be considered as iterating infinitely:

for (;;)

    statement

This is equivalent to:

while (true)

    statement

Exercise 3.7: Using a for Loop to Print the Days of the Week

In this exercise, we will iterate through an array created to store the days of the week using a for loop and print the days. We will restrict the loop iterations so that the loop doesn't go beyond the array elements present:

  1. Create a PHP file named print-days-for.php.
  2. Add the $days array with the names of the seven days of the week, as follows:

    <?php

    $days = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

  3. Add a for loop with the three expressions, as in the following code:

    <?php

    $days = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

    $totalDays = count($days);

    for ($i = 0; $i < $totalDays; $i++) {

        echo $days[$i] . " ";

    }

    //outputs

    //Saturday Sunday Monday Tuesday Wednesday Thursday Friday

    Here, the $totalDays is the variable that holds the count of the days. The number of iterations can be controlled by the $i < $totalDays expression since $i has been started with 0, which is the first index of the array, so that the loop executes exactly the number of elements (days) available in the $days array. With the completion of each iteration, the index value in $i is incremented by the $i++ statement so that we can access the next value within the array.

  4. Run the PHP file from a Terminal or console with the following command:

    php print-days-for.php

    The script prints the names of the seven days of the week from the given array:

    Figure 3.16: The for loop output

  5. Tweak the script with different loop expressions and rerun it to see the new outputs.

The foreach Loop

So far, we've seen how a for loop can leverage a loop step variable as an index to access an array, but the approach is not feasible for iterating through an associative array where you want to use the index or the key as meaningful data. Consider a person's information array or an object example, where a person's attributes, such as first name, last name, age, email, and so on, have been stored against the same attribute names as the keys, so that each key defines what type of information has been stored against that index.

In such scenarios, to iterate through an object or an array, we need a specialized looping construct – a foreach loop.

With a foreach loop, PHP supports implicit looping through all elements of an array or an object.

The syntax of a foreach loop is as follows:

foreach (array_expression as $value)

    statement

array_expression provides an array to iterate over. With each iteration, the value of the current element assigned to $value and the array pointer is incremented by one.

The foreach loop can also be written in the following form:

foreach (array_expression as $key => $value)

    statement

In this form, with each iteration, the current element value is assigned to the $value variable, and its corresponding key is assigned to the $key variable.

In a foreach loop, rather than the Boolean evaluated conditions, the size of the array controls how many times a loop executes.

Exercise 3.8: Using a foreach Loop to Print the Days of the Week

In this exercise, we will iterate through an array of the names of the days of the week, using a for loop and print the days. We will restrict the loop iterations so that the loop doesn't go beyond the array elements present:

  1. Open the print-days-for.php PHP script and copy the contents into a new file named print-days-foreach.php.
  2. Replace the for loop with a foreach loop:

    <?php

    $days = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

    foreach ($days as $day) {

        echo $day . " ";

    }

    //outputs

    //Saturday Sunday Monday Tuesday Wednesday Thursday Friday

    In the preceding example, the size of the array controls how many times the foreach loop executes. So, for each element in the array, starting from the first, the looping control statement assigns the element value to a variable and iterates to execute the statements in the enclosed block.

  3. Run the PHP file from a Terminal or console with the following command:

    php print-days-foreach.php

    The script prints the names of the seven days from the given array:

Figure 3.17: The foreach loop output

Nesting Loops

With increasing program complexity, you may find yourself in a position where a single loop may not be able to achieve your program's objectives. In such cases, we can use loops within loops; in other words, nested loops.

To achieve nesting, one loop can be used inside the enclosure of another loop. With the first iteration of the outer loop, the inner loop is executed to run through the given number of iterations. Again, with the next outer iteration, the inner loop is triggered and it completes all its iterations. An inner loop structure can be considered as another statement among enclosed statements. Obviously, we can use break and continue (which will be discussed in the next section) statements to interrupt the flow of the iteration.

For example, the for loop can be used as a nested form, as follows:

$basket = [

                ["Mango", "Apple", "Banana", "Orange"],

                ["Burger", "Fries", "Sandwich", "Brownie", "Soda"]

        ];

for ($i = 0; $i < count($basket); $i++) {

        for ($j = 0; $j < count($basket [$i]); $j++) {

                echo $basket[$i][$j]  . PHP_EOL;

        }

}

This will output the following:

Mango

Apple

Banana

Orange

Burger

Fries

Sandwich

Brownie

Soda

Here, you can see that two for loops have been used to iterate through the two-dimensional array and we have used $i & $j to generate the indexes to access their corresponding values.

Instead of a for loop, we could have used two foreach loops, as follows:

$basketItems = [

               ["Mango", "Apple", "Banana", "Orange"],

               ["Burger", "Fries", "Sandwich", "Brownie", "Soda"]

               ];

foreach ($basketItems as $foodItems) {

        foreach ($foodItems as $food) {

                echo $food . PHP_EOL;

        }

}

This will output the following:

Mango

Apple

Banana

Orange

Burger

Fries

Sandwich

Brownie

Soda

Notice that the foreach loop eliminates the use of an index to access an element of an array, so the foreach loop is useful for iterating such arrays.

Exercise 3.9: Using Nested foreach Loops

In this exercise, we will practice loop nesting and will demonstrate how inner and outer loops work. We will loop through an array of different professions and print each profession. By using a condition, if the profession is equal to "Teacher", then we'll loop through another array of subjects and print out the subjects as well.

We can make the inner loop iterate based on a precondition; that is, when the profession is teacher. We will enclose the inner loop that prints the subject name from the subjects' array in an if control structure:

  1. Create a PHP script named print-professions-subjects.php.
  2. Declare the professions in an array, as follows:

    <?php

    $professions = ["Doctor", "Teacher", "Programmer", "Lawyer", "Athlete"];

  3. Declare the subjects in an array, as follows:

    <?php

    $professions = ["Doctor", "Teacher", "Programmer", "Lawyer", "Athlete"];

    $subjects =  ["Mathematics", "Computer Programming", "Business English", "Graph Theory"];

  4. Add a foreach loop to iterate through the $professions array, as follows:

    <?php

    $professions = ["Doctor", "Teacher", "Programmer", "Lawyer", "Athlete"];

    $subjects =  ["Mathematics", "Computer Programming", "Business English", "Graph Theory"];

    foreach ($professions as $profession) {

            echo "The Profession is $profession. " . PHP_EOL;

    }

    The output is as follows:

    The Profession is Doctor.

    The Profession is Teacher.

    The Profession is Programmer.

    The Profession is Lawyer.

    The Profession is Athlete.

  5. Add the following inner foreach loop to print the subjects if the profession is teacher, as follows:

    <?php

    $professions = ["Doctor", "Teacher", "Programmer", "Lawyer", "Athlete"];

    $subjects =  ["Mathematics", "Computer Programming", "Business English", "Graph Theory"];

    foreach ($professions as $profession) {

            echo "The Profession is $profession. " . PHP_EOL;

            if ($profession === 'Teacher') {

                    foreach ($subjects as $name) {

                            echo " $name " . PHP_EOL;

                    }

            }

    }

    The output is as follows:

    The Profession is Doctor.

    The Profession is Teacher.

    Mathematics

    Computer Programming

    Business English

    Graph Theory

    The Profession is Programmer.

    The Profession is Lawyer.

    The Profession is Athlete.

    Here, we have two different arrays. The professions array contains the profession names, while the $subjects array holds the subject name that is to be printed if the profession name matches the "teacher" string. We have used a foreach loop to iterate through the $professions array. The first foreach loop should be considered an outer loop.

    The outer loop prints the profession name, and then tests the condition, which matches the profession name, Teacher. If the profession matches Teacher, then execute the inner foreach loop. The inner loop iterates through the $subjects array to print the subject's name.

  6. Run the PHP file from a Terminal or console with the following command:

    php print-professions-subjects.php

    The script prints the profession name from the given array and if the profession is Teacher, then it prints the subject's name from the given $subjects array:

    Figure 3.18: The nested foreach loop output

    As you can see, the inner loop has been triggered based on a precondition, meaning we have used a looping and a branching technique here. We will achieve both by using a for loop in the next step.

  7. Modify print-professions-subjects.php and replace the inner loop as follows:

    <?php

    $professions = ["Doctor", "Teacher", "Programmer", "Lawyer", "Athlete"];

    $subjects =  ["Mathematics", "Computer Programming", "Business English", "Graph Theory"];

    $totalSubjects = sizeof($subjects);

    foreach ($professions as $profession) {

            echo "The Profession is $profession. " . PHP_EOL;

            for ($i = 0; $profession === 'Teacher' && $i < $totalSubjects; $i++) {

                    echo " ". $subjects[$i] . PHP_EOL;

            }

    }

    The output is as follows:

    The Profession is Doctor.

    The Profession is Teacher.

    Mathematics

    Computer Programming

    Business English

    Graph Theory

    The Profession is Programmer.

    The Profession is Lawyer.

    The Profession is Athlete.

    Here, the second expression in the for loop supports the condition expression, so we have composed the expression with two conditions: one that checks whether the profession is Teacher and another that checks that the array index doesn't exceed the size of the $subjects array. The sizeof() function is used to determine the number of elements in the array.

  8. Run the PHP file from a Terminal or console with the following command:

    php print-professions-subjects.php

    The script prints just the same as in step 6.

Similarly, we can implement the inner loop with any looping techniques, such as while or do…while and rerun the PHP file to see the output.

The break Statement

We have looked at several loops and their implementations so far. However, you may come across situations where breaking a loop is necessary. For example, in addition to a loop conditional expression, we might want to terminate the loop from iterating further based on a condition checked inside the loop. In such cases, break is quite useful to terminate the innermost loop, providing another control for such looping structures.

An early exit from the loop is possible using the break; statement. break immediately terminates the execution of any running loop.

The break statement supports an optional argument that determines the execution of how many enclosed structures are to be broken out. With a default argument of 1, an immediate enclosing looping structure can be broken out. To break out multiple enclosed looping structures, we need to supply a numeric argument; for example, break 2.

As in the following example:

break;

//or

break n;

Check out the following example, which breaks two enclosed loopings:

for(;;){

     for(;;){

           break 2;

     }

}

Both for loops should iterate for an infinite time, and to escape them both we need to provide a break argument of 2. We can safeguard a break statement like this with an if control structure so that we don't exit the loop without a condition.

Exercise 3.10: Using a break Statement to Terminate a Loop's Execution

We will take the previous exercise of the while loop to check whether the number is equal to 8, then print ends the execution of loop, and then end the loop using a break statement:

  1. Copy the contents from the print-numbers-while.php file and create a PHP filename, print-numbers-break.php, with the copied contents.
  2. Add a conditional break statement in the while loop's body, as follows:

    <?php

    $number = 1;

    while ($number <= 10) {

            echo $number . " ";

            if ($number === 8) {

                    echo "ends the execution of loop.";

                    break;

            }

            $number++;

    }

    //outputs

    // 1 2 3 4 5 6 7 8 ends the execution of loop.

    Here, we have checked that $number is equal to 8 with a conditional expression, then printed the given message and terminated the execution. The break statement has been placed inside the loop, meaning when the break; expression is executed, the loop can be terminated regardless of whether the looping condition says that the loop still has two more iterations.

  3. Run the PHP file from a Terminal or console with the following command:

    php print-numbers-break.php

    After printing 8, the loop prints the ends the execution of loop. message and terminates the subsequent iterations with a break:

Figure 3.19: The break output

The continue Statement

In any loop, we might want to skip any specific iteration based on a certain condition. For example, printing the numbers 1 through 10, we might want to skip the odd numbers and print the even numbers only. To continue with the next iteration and skip the rest of the execution within the enclosed structure, the continue statement can be used.

The continue statement supports an optional numeric argument such as the break statement, which specifies how many levels of enclosing loops it should skip to the end of the current iteration(s). The default value, 1, skips to the end of the current iteration and continues with the rest of the iterations.

Exercise 3.11: Using continue to Skip an Item in a List

In earlier looping examples, we created a script to print numbers 1 through 10. In this exercise, we will take the previous exercises on loop techniques to check whether a number is equal to 8, then skip printing the number and continue printing the rest:

  1. Create a PHP file named print-numbers-continue.php.
  2. Add a for loop like the following to print numbers 1 through 10:

    <?php

    for ($i = 1; $i <= 10; ++$i) {

        print "$i ";

    }

    //outputs

    //1 2 3 4 5 6 7 8 9 10

  3. Add the following continue statement if the number is equal to 8:

    <?php

    for ($i = 1; $i <= 10; ++$i) {

        if ($i == 8) {

            continue;

        }

        print "$i ";

    }

    //outputs

    //1 2 3 4 5 6 7 9 10

    Here, we checked whether $i is equal to 8 with a conditional expression, then we executed the continue; statement. So, from that particular point, the iteration skips the rest of the execution and goes for the next iteration. Hence, the print command for the number 8 can be skipped and it can continue printing 9 and 10.

  4. Run the PHP file from a Terminal or console with the following command:

    php print-numbers-continue.php

    After printing 7, the loop skips printing 8 and continues printing the rest of the numbers:

Figure 3.20: The break script output

Note

To exit a loop, a common practice is to use a conditional statement that evaluates to false, else keep iterating. The break and continue statements can be used as a special way of getting out of a loop or skipping the rest of the execution in the current execution.

Alternative Control Syntaxes

PHP supports an alternative way of writing control structures. As per the alternate syntax, we will replace the initial brace with a colon and the closing brace with a structure ending statement such as endif, endswitch, endfor or endwhile.

For example, if...else becomes the following:

if (expression):

     statement1

     statement2

     …

endif;

Or, the if…elseif…else syntax with the structure ending statement looks as follows:

if (expression1):

     statement1

     statement2

     …

elseif (expression2):

     statement3

     …

else:

     statement4

     …

endif;

The while loop becomes the following:

while (expression):

     statement

endwhile;

The same goes for the for loop:

for (expr1; expr2; expr3):

     statement1

     statement2

     …

endfor;

So, it is up to us which syntax we follow. The alternative syntax is supported for users of the earlier versions of PHP. Generally, this book follows the standard syntax throughout the book.

Note

PHP alternative syntaxes can be found at this link: https://packt.live/2M0IMli.

Using System Variables

Command-line arguments can be obtained using the $argv system variable. We will use $argv[1] and $argv[2] to obtain the second and third arguments.

Note

$argv[0] is the script name in this case.

Command-line arguments can be passed as follows:

<?php

$varA = $argv[1] ?? 5;

$varB = $argv[2] ?? 5;

Here, the ?? the null coalescing operator is used so that if $argv[1] or $argv[2] does not exist or is NULL then, we can assign a default number, 5, to the $varA and $varB limit variables.

Activity 3.1: Creating a Movie Listing Script to Print Movies per Director

In this activity, we will practice nested looping and apply conditions to restrict the iterations of inner and outer loops. We will have a multi-dimensional associative array where the director's name acts as the key to hold an array of movie names. So, each element of the associative array contains a director's name as a key and the movie names array as a value. We will introduce an outer loop to loop through the associative array elements and print the director's name, used as a key. Another inner loop should loop through the movie names array of that director – that is the key. The arguments act as loop iteration steps to maintain where the first argument defines how many times a director's name should be printed and the second argument defines how many movie names should be printed from the given director.

The multi-dimensional array contains five directors.

The steps to be performed are as follows:

  1. Create the activity-movies.php script file, which takes two arguments, both numerical: the first argument will be used for the number of directors, and the second one will be used for the number of movies.
  2. Add a nested array containing a list with five directors, each entry containing a list of five movie titles.
  3. By running the script, print the list of directors and the movie titles, as required by the input arguments.
  4. If the input arguments are not passed, then consider the default value of 5 for both.
  5. Here's some sample output of running the php activity-movies.php 3 2 script:

    Steven Spielberg's movies:

      > The Post

      > Bridge of Spies

    Christopher Nolan's movies:

      > Dunkirk

      > Quay

    Martin Scorsese's movies:

      > The Wolf of Wall Street

      > Hugo

    Note

    The solution for this activity can be found via this link.

Tips for Control Structures

Here are some best practices while working with control structures:

  • If you need multiple if or elseif statements, you might consider replacing them with a switch case as a switch statement is faster.
  • Avoid deeply nested control structures such as if { if { if { ... }}} or for(;;) { for(;;){ for (;;){ … } } } as deep nesting ties one condition to another and when we need to make a modification to our tied conditions, we might spend a big chunk of time on code maintenance.
  • It is a common mistake to put duplicate code under different branches, hence those branches become the same, so consider refactoring the code; the goal of each branch should be different.
  • foreach is a better choice for associative arrays or objects.
  • Learn to identify whether you need bounded or unbounded loops.
  • Be careful when using unbounded loops that are controlled by a condition, so that they don't run to infinity.

Summary

Control statements are at the heart of computer programming. They are all about evaluating conditions to perform a certain block of code once or in a loop. To craft Boolean expressions, we have applied Boolean constants, Boolean values in variables, and logical operators. Also, logical and relational comparison can be applied to expressions that are to be used as a precondition for a branch of code.

To deal with complex scenarios, we learned how easily we can compose nested control structures and how we can conditionally break out of a branch or skip a certain loop iteration. We also learned to avoid deep nesting to reduce the amount of time spent on future code maintenance. We need to carefully decide which branching or looping technique is suitable for a specific scenario and we need to be certain that our loops do not run to infinity.

Finally, having reached the end of this chapter, we should be able to write smaller sized scripts to perform operations that involve condition evaluations, array or object iterations, applying a condition to terminate an execution flow, comparisons among data to classify or categorize items, doing repetitive tasks, and much more.

In our next chapter, we will group a block of code as a unit named function to reuse these functions wherever we need to execute that block of code. For example, we might need to validate a data type associated with a variable at multiple places in our code. Instead of writing the data type validation code multiple times, we can shift the validation code into a function and use or call that function whenever we need that data type validation. So, the next chapter will introduce you to how to reuse code and how to write code in units.