Home > Articles > Programming > PHP

This chapter is from the book

3.2 Control Structures and Operators

Usually programs need so-called control structures, which are used to decide at runtime what a program has to do. Flow control is an important part of every programming language and is essential for building applications. PHP provides a broad range of methods, as you will see in this section.

3.2.1 Operator and IF/ELSE/ELSEIF Statements

Use if to check whether a certain expression is true or not. If is supported by all commonly used programming languages such as C/C++, Java, Perl, and Python, and therefore it is a fundamental instrument of every computer programmer. To show you how conditions can be checked using if, we include a short example:

<?php
    if   (2 > 1)
    {
        echo '2 is higher than 1<br>';
    }
?>

A message will be displayed on the screen because 2 is higher than 1. If the condition wasn't fulfilled, nothing would be displayed.

NOTE

If an empty document is returned by PHP, an error will be raised by some browsers.

Normally if is used to decide whether or not something has to be done. If a certain condition is fulfilled, PHP will execute the code in parentheses, but what has to be done if a condition is not fulfilled? If is very often used in combination with else. Every time an expression in the if statement returns false, the code of the else branch will be executed. Using if in combination with else is an extremely comfortable feature because it makes programming much easier and helps you to avoid bugs. In the next example you will learn how to use if and else:

<?php
    $a=23;
    $b=34;
 
    if   ($a > $b)
    {
        echo 'a is higher than b';
    }
    else
    {
        echo 'b is higher than a';
    }
?>

First, we initialize two variables. $a is set to 23 and 34 is assigned to $b. In the next step we check if $a is higher than $b. If the expression returns true, a is higher than b will be displayed on the screen. Otherwise, b is higher than a will be the result of the program.

In the next example you will see what you can do if you want a message to be displayed if $b is higher than $a and $b is higher than 30:

<?php
    $a=23;
    $b=34;
 
    if   ($a > $b)
    {
        echo 'a is higher than b';
    }
    else
    {
        if   ($b > 30)
        {
            echo 'b is higher than a and higher than 30.';
        }
    }
?>

$a is lower than $b, so PHP will execute the else branch. In the else branch you use a second if statement to find out if $b is higher than 30. It is an easy task to solve the problem the way it is shown in the previous example, but it is not the most elegant way:

<?php
    $a=23;
    $b=34;
 
    if   ($a > $b)
    {
        echo 'a is higher than b';
    }
    elseif ($b > 30)
    {
        echo 'b is higher than a and higher than 30.';
    }
?>

Instead of using a second if statement in the else branch, it is also possible to use elseif, which is in most cases the shorter and more elegant way.

Sometimes it is necessary to find out if two or more conditions are fulfilled. Therefore multiple expressions can be combined using operators and parentheses. Assume that you want to check whether $a is higher than 10 but lower than 50:

<?php
    $a=23;
 
    if   ($a > 10 && $a < 50)
    {
        echo "$a higher than 10 and lower than 50";
    }
?>

You can use the && operator to tell PHP that both conditions have to be fulfilled; otherwise, false will be returned and the else branch, which does not exist in our example, will be executed. && is equal to and, so it does not matter if we use ($a > 10 and $a < 50) or ($a > 10 && $a < 50) in our example. Using && instead of and is the more common way because && is also supported by programming languages like C/C++ and Perl. If you execute the example, the result will be 23 higher than 10 and lower than 50.

The counterpart of and is the or operator. If or is used, true will be returned if one expression returns true. Let's have a look at an example:

<?php
    $a=2;
 
    if   ($a > 10 || $a < 50)
    {
        echo "$a higher than 10 or lower than 50";
    }
?>

You want a string to be printed on the screen if $a is either higher than 10 or lower than 50. If one of those conditions is fulfilled, the string will be displayed. The number 2 is not higher than 10 but lower than 50, so we can find 2 higher than 10 or lower than 50 printed on the screen. Instead of || you can also use or.

Another important operator is the xor operator. False is returned if both values are the same; otherwise, the result is true. The next example demonstrates the usage of xor.

<?php
    $a=18;
    $b=19;
 
    if   ($a xor $b)
    {
        echo '$a and $b are the same';
    }
    else
    {
        echo '$a and $b are not the same';
    }
?>

As you might have expected, $a and $b are not the same is returned by the script.

So far, you have learned to use &&, ||, and xor. Now it is time to use these operators as a team to build more complex expressions. Assume that you want a string to be displayed if $a is higher than 10 and lower than 20 or exactly 2. In this case it is necessary to group expressions:

<?php
    $a=2;
 
    if   (($a > 10 && $a < 20) || $a == 2)
    {
        echo "$a higher than 10 but lower than 20 or exactly 2";
    }
?>

The first expression consists of two parts, which are connected using &&. If all expressions in parentheses are fulfilled, the first part will return true. If either the first or the second part of the entire expression returns true, the result will be true. In your case the second part of the expression is an exact match, so the entire expression is true.

Those among you who haven't done a lot of computer programming yet might wonder why == is used instead of = in the example you have just seen. It is not a typo. == is used to check whether two variables are the same. =, however, is used to find out whether a variable can be assigned to another variable. Let's have a look at a very simple example:

<?php
    $a=18;
 
    if   ($a = $b)
    {
        echo '$a can be assigned to $b';
    }
    else
    {
        echo '$a cannot be assigned to $b';
    }
?>

First, a value is assigned to $a. In the next step you try to find out if $b can be assigned to $a. Therefore you have to use the = operator. Because $b hasn't been used yet, the else branch will be executed.

If statements can also be used to find out whether a variable has already been defined. As you will see in the section called "Working with Forms," later in this chapter, checking variables is essential for every PHP program. The next example shows how you can find out whether a variable has already been in use:

<?php
    if   ($a)
    {
        echo '$a has already been defined';
    }
    else
    {
        echo '$a has not been defined yet';
    }
?>

In this case the result will be $a has not been defined yet because $a has not been used before.

3.2.2 WHILE and DO..WHILE

WHILE loops are very widespread in programming languages. Like almost all other programming languages, PHP provides WHILE loops, but what are WHILE loops good for? WHILE loops are used to execute a piece of code multiple times. Here is an example of a simple WHILE loop:

<?php
    echo '<html><body>';
 
    $a=1;
 
    while  ($a <= 5)
    {
        echo "a: $a<br>\n";
        $a++;
    }
    echo '</body></html>';
?>

The numbers from one to five are displayed. First, some HTML code is generated. In the next step we set $a to 1 and start the loop. The code between the curly brackets has to be executed until $a is higher than 5. Every time the loop is processed, a: and the content of $a are displayed on the screen. After that $a is incremented by one. The ++ operator is very often used in languages like C and C++. As you can see, it is also available in PHP. $a++ is equal to $a=$a+1.

Let's have a look at what is displayed in the browser when we execute the script:

a: 1
a: 2
a: 3
a: 4
a: 5

As we have promised, the numbers from 1 to 5 are displayed. The HTML code you generated will not be displayed on the screen because it is used only by the browser.

The syntax that has just been described is the most commonly used way of using WHILE loops. However, PHP provides an additional way of using WHILE:

<?php
    echo '<html><body>';
 
    $a=1;
 
    while  ($a <= 5):
        echo "a: $a<br>\n";
        $a++;
    endwhile;
    echo '</body></html>';
?>

The code shown in the preceding listing is equal to the code you have seen before. The only difference is the way WHILE is used. In the second example you don't use curly brackets, so you have to tell PHP when the loop ends. This is done using endwhile.

If you are using loops, make sure that the condition that makes the loop stop will be false after executing the loop for the desired number of times; otherwise, the loop will run until one of the components (PHP, the kernel, the Web server, and so forth) stops the execution of the script. In your case you'd have an endless loop if $a was never incremented. Endless loops are very dangerous and you have to keep that in mind. PHP offers an option in php.ini to limit both the memory consumption and runtime of a PHP script. We highly recommend setting these options to a reasonable value.

Sometimes it is necessary to execute the code of a loop once and to check the condition for stopping the loop after that. For that PHP offers do..while loops:

<?php
    echo '<html><body>';
 
    $a=6;
 
    do
    {
        echo "a: $a<br>\n";
    }
    while  ($a <= 5);
    echo '</body></html>';
?>

First, 6 is assigned to $a, and then we start the loop using do. $a, which is 6, is displayed on the screen and you check if the loop has to be executed again. Because 6 is higher than 5, the echo command won't be executed again. In this case you are lucky because if $a was lower than 6, you'd run into an infinite loop. $a is not increased, so ($a <= 5) would always be true.

What can you do if you have to leave a loop in the middle of a block? PHP has the right solution for you. Break is a command that can be used to stop all kinds of loops in the middle of a block. Here is an example:

<?php
    echo '<html><body>';
 
    $a=1;
 
    do
    {
        echo "a: $a<br>\n";
        $a++;
        if   ($a == 3)
        {
            break;
        }
    }
    while  ($a <= 5);
    echo '</body></html>';
?>

You want to execute the loop as long as $a is lower than 6, but if $a is equal to 3, you want to exit the while loop.

If you execute the script, you can see the result in the browser:

a: 1
a: 2

Two lines will be displayed because the loop is interrupted after printing two lines on the screen.

Continue is another important keyword when dealing with loops. Continue is used to stop the execution of a block without leaving the loop. The idea is to ignore steps in the loop. Here is an example:

<?php
    echo '<html><body>';
 
    $counter=0;
    $test=10;
    while ($counter < $test)
    {
        if   ($counter %2)
        {
            $counter++;
            continue;
        }
        echo "Current value of counter: $counter<br>";
        $counter++;
    }
 
    echo '</body></html>';
?>

The loop is executed until $counter is equal to $test. In the loop you try to find out if $counter can be divided by two. If the result is different from 0 (in your case if it is 1), increment the counter and use continue. The program will start to check the condition again and if it is still true, the block will be executed again.

The output of the script is not surprising:

Current value of counter: 0
Current value of counter: 2
Current value of counter: 4
Current value of counter: 6
Current value of counter: 8

One line is generated for every second number the loop is processed for.

Continue can also be used to leave more than just one loop. Let's have a look at the next example:

<?php
    echo '<html><body>';
 
    $counter=0;
    while ($counter == 0)
    {
        $counter++;
        $inner=0;
        while  ($inner == 0)
        {
            $inner++;
            continue 2;
            echo "inner<br>";
        }
        echo "middle<br>";
    }
    echo "outer<br>";
 
    echo '</body></html>';
?>

You can see two while loops. Every loop is entered, but in the inner loop you call continue with a parameter to tell PHP how many loops have to be left. In this case you tell PHP to leave two loops, so the result is outer. Nothing else is displayed on the screen. Very efficient applications can be built by using continue with parameters, but this is also very dangerous because a programmer can easily lose the overview of the logic flow of the source code.

3.2.3 FOR

If a block has to be executed a fixed number of times, it is recommended to use for loops instead of while loops.

A for loop consists of a starting value, a condition that is checked every time the loop is processed, and an expression that is executed after every time the loop is processed. Let's have a look at an example:

<?php
    echo '<html><body>';
 
    for($i = 0; $i < 5; $i++)
    {
        echo "i: $i<br>\n";
    }
 
    echo '</body></html>';
?>

You want to display the numbers from 0 to 4 on the screen. Therefore a for loop has been implemented in the script. The loop starts with $i being 0 and it is executed as long as $i is lower than 5. The third parameter tells PHP to increment $i after every time the loop is processed. The output of the script shows what comes out when you start the program using a Web browser.

i: 0
i: 1
i: 2
i: 3
i: 4

Sometimes it is necessary to implement more powerful and more complex for loops. Just as in many other languages like C or C++, a list of conditions can be used in combination with for loops. This feature is very important because it allows you to implement complex features with little effort:

<?php
    echo '<html><body>';
 
    for($i = 0, $j = 10; $i < 5, $j > 0; $i++, $j = $j - 2)
    {
        echo "i: $i --- j: $j<br>\n";
    }
 
    echo '</body></html>';
?>

All three parameters consist of a list of expressions used to process a certain variable. The text generated by the program shows what has happened to the variables in the program:

i: 0 --- j: 10
i: 1 --- j: 8
i: 2 --- j: 6
i: 3 --- j: 4
i: 4 --- j: 2

$i was incremented by one, whereas $j was reduced by two every time the loop was processed. Using the syntax you have just seen allows you to treat multiple variables using just one for loop. The list of operations used in the loop can easily be extended to the desired complexity.

Up to now, you have learned to use for loops with a list of expressions. However, in PHP, programmers are not forced to provide a list of at least one parameter because it is also possible to leave the list empty, as shown in the following example:

<?php
    echo '<html><body>';
 
    $i=0;
    for   (; $i < 5; )
    {
        echo "i: $i<br>\n";
        $i++;
    }
 
    echo '</body></html>';
?>

The first and the third parameter of the for loop are empty. The result of the loop is still a list of all numbers from 0 to 4, but it has been generated differently. $i is initialized in the line before the loop starts and it is incremented after displaying the output on the screen:

i: 0
i: 1
i: 2
i: 3
i: 4

As you can see, there are many ways to solve the problem because PHP has a comparatively rich syntax. For those of you out there who are interested in writing very short and efficient code, the next example might be of interest:

<?php
    echo '<html><body>';
    for   ($i = 0; $i < 5; print "i: $i<br>", $i++);
    echo '</body></html>';
?>

The output of the script is still the same, but we needed only one line to print the numbers on the screen. As you can see, PHP allows you to use any kind of expressions in a for loop, which makes that kind of loop extremely flexible.

3.2.4 SWITCH

To avoid long sequences of if statements, it is sometimes possible to use switch and case statements instead. Switch and case are often used to find the right piece of code that has to be executed from a list of possibilities. Let's have a look at the next example:

<?php
    $a=2;
 
    switch ($a)
    {
        case 1:
            echo "case 1: \$a is $a<br>";
            break;
        case 2:
            echo "case 2: \$a is $a<br>";
            break;
        case 3:
            echo "case 3: \$a is $a<br>";
            break;
    }
?>

First, 2 is assigned to $a. The switch statement checks all cases and if the right value is found, the branch is entered and PHP executes all the code until a break command is found. If you execute the script, one line will be displayed:

case 2: $a is 2

The same result can also be achieved by using if statements instead of switch and case:

<?php
    $a=2;
 
    if   ($a == 1)
    {
            echo "case 1: \$a is $a<br>";
    }
    if   ($a == 2)
    {
            echo "case 2: \$a is $a<br>";
    }
    if   ($a == 3)
    {
            echo "case 3: \$a is $a<br>";
    }
?>

You can print the string $a on the screen. The $ character has to be escaped using a backslash because otherwise PHP would display the content of the variable $a instead of the string $a on the screen.

In the next step you will try to use switch and case without using break as well:

<?php
    $a=2;
 
    switch ($a)
    {
        case 1:
            echo "case 1: \$a is $a<br>";
        case 2:
            echo "case 2: \$a is $a<br>";
        case 3:
            echo "case 3: \$a is $a<br>";
    }
?>

The result of the version using no break commands differs significantly, as you can see in the following example:

case 2: $a is 2
case 3: $a is 2

All of a sudden two lines are returned and that is definitely not the result you want. PHP searches for the right value and executes the code until a break command is found. In your case no break commands are in the code, so it is executed until the end. In some cases this might be the desired behavior of the program, but in most cases it is not.

Another feature of switch and case is the ability to handle default values. If no value in the list matches, PHP will execute the default branch. In the following example, you are looking for 9, but 9 is not listed in the switch statement:

<?php
    $a=9;
 
    switch ($a)
    {
        case 1:
            echo "case 1: \$a is $a<br>";
            break;
        case 2:
            echo "case 2: \$a is $a<br>";
            break;
        default:
            echo "the value couldn't be found<br>";
    }
?>

PHP will execute the default code because 9 has not been found in the list:

the value couldn't be found

As we have already mentioned, you can make a workaround using if statements instead of switch and case, but this can be far more complex especially when default values are involved and some of your branches do not contain break statements. Let's have a look at the next example. The target is to display 1 and 2 on the screen if the switch statement is called with $a being 1. In all other cases, only the value switch is called with should be displayed:

<?php
    $a=1;
 
    switch ($a)
    {
        case 1:
            echo '1<br>';
        case 2:
            echo '2<br>';
            break;
        case 3:
            echo '3<br>';
            break;
        default:
            echo 'default';
    }
?>

The task is easy because the only thing you have to do is to write a switch block where every entry but the first one contains a break command.

Switch and case constructions are a very flexible and powerful feature of PHP. It is possible to build sophisticated applications without having to use complex if/else constructs.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020