2.6. Control Structures

To add power and convenience to your scripts, PHP supports a number of conditional statements, loops, and other control structures that allow us to manipulate data easily throughout your code.

The control structures supported by PHP are:

  • if

  • else

  • elseif/else if

  • while

  • do-while

  • for

  • foreach

  • break

  • continue

  • switch

  • return

  • require

  • include

  • require_once

  • include_once

  • goto

2.6.1. if, else, and else if

The most basic control structure is the if statement. It defines a block of code between curly braces ({}) that is to be executed only if a condition is met:

<?php

    $foo = 5;

    if($foo < 10) {
        echo "The condition was met. <br />";
    }

?>

In this program, nothing is output if $foo doesn't meet your condition. In some cases, this is an unacceptable result, so you would need to use an else statement to provide an alternative value to output if the condition isn't met:

<?php

    $foo = 15;

    if($foo < 10) {
        echo "The condition was met. <br />";
    } else {
        echo "The condition was not met. <br />";
    }

?>

If you have a value that failed the if condition, but you aren't ready to pass it to the else statement yet, you can add an elseif statement to be evaluated. You place this new statement between the if and else blocks; it executes only if the first condition isn't met, but the second is:

<?php

if($age < 18) {
    echo "Not old enough to vote or drink! <br />";
} else if ($age < 21) {
    echo "Old enough to vote, but not to drink. <br />";
} else {    // If we get here, $age is >= 21
    echo "Old enough to vote and drink! <br />";
}

?>

2.6.2. while and do-while

The while loop allows you to repeat a block of code continuously for as long as a condition is TRUE. This allows you to cycle through data sets without needing to know how many exist; all that matters is the number of datasets you want to use at a maximum.

In this example, you use a counter variable ($i) that stores the count, incrementing this at the end of each loop cycle. When the counter reaches three, the condition is no longer true, so the loop ends. Place this code in test.php:

<?php
    $i = 0;
    while($i<3) {
        echo "Count is at $i. <br />";
        ++$i;
    }
?>

Loading this script in a browser produces the following output:

Count is at 0.
Count is at 1.
Count is at 2.

NOTE

Keep in mind that the loop will not execute if the condition isn't met. In the previous example, no output would be generated if $i were set to 4.

A more practical example is looping through an array to generate output based on the stored values. You can add the following code to test.php to output a list of bands:

<?php

    $bands = array("Minus the Bear", "The Decemberists",
        "Neko Case", "Bon Iver", "Now It's Overhead");

    $i = 0;
    $n = count($bands); // Stores the number of values in the array
    while($i < $n) {
        echo $bands[$i], "<br />";
        ++$i;
    }

?>

This loop produces the following output when loaded in a browser:

Minus the Bear
The Decemberists
Neko Case
Bon Iver
Now It's Overhead

You need to use a do-while loop if you want to set up a loop that executes at least once, then continues if the condition is met:

<?php
    $i = 10;

do {
        echo "The count is at $i.
";
        ++$i;
    } while($i<5);

    // Outputs "The count is at 10."
    // even though $i doesn't meet the condition.
?>

2.6.3. for

One of the most versatile statements in PHP programming is the for loop, which accepts three expressions: expression one is evaluated once at the beginning of the loop, unconditionally; expression two is evaluated at the beginning of each iteration of the loop, and the loop continues only if the expression evaluates to true; expression three is evaluated at the end of each iteration.

Each expression can have more than one part, with each part separated by a comma. You separate the three main expressions using semicolons:

<?php
    for($i=0; $i<3; ++$i) {
        echo "The count is at $i.
";
    }

    // Output:
    // The count is at 0.
    // The count is at 1.
    // The count is at 2.
?>

At this point, you might find it helpful to revisit the previous code example where you created a list of bands. This code produces output identical to the while loop you used previously, while also cleaning up the code a bit:

<?php

    $bands = array("Minus the Bear", "The Decemberists",
        "Neko Case", "Bon Iver", "Now It's Overhead");

    for($i=0, $n=count($bands); $i<$n; ++$i) {
        echo $bands[$i], "<br />";
    }

?>

2.6.4. foreach

The foreach loop provides a powerful option for cases where you deal with arrays. Continuing with the code example that outputs a list of bands, you can use foreach to cycle quickly through the array elements:

<?php

    $bands = array("Minus the Bear", "The Decemberists",
        "Neko Case", "Bon Iver", "Now It's Overhead");

    foreach($bands as $band) {
        echo $band, "<br />";
    }

?>

The foreach loop lets you iterate through an array and treat each array element as an individual variable; this makes for very readable code.

If the array is associative, you also have the option to separate the array key as a variable. This proves useful in some cases. For example, add the following code in test.php:

<?php

    $person = array(
        'name' => 'Jason',
        'age' => 23,
        'passion' => 'craft beer'
    );

    foreach($person as $key => $value) {
        echo "His $key is $value. <br />";
    }

?>

The preceding snippet produces the following output when you load it into a browser:

His name is Jason.
His age is 23.
His passion is craft beer.

If you're dealing with multidimensional arrays, you can nest your foreach statements to access the different keys and values. Simply add the following code to test.php:

<?php

$people = array(
        'Jason' => array(
            'gender' => 'male',
            'hair' => 'brown'
        ),
        'Carly' => array(
            'gender' => 'female',
            'hair' => 'blonde'
        )
    );

    foreach($people as $name => $person) {
        foreach($person as $key => $value) {
            echo "$name's $key is $value. <br />";
        }
    }

?>

This code produces the following output:

Jason's gender is male.
Jason's hair is brown.
Carly's gender is female.
Carly's hair is blonde.

2.6.5. break

In any loop, the break statement causes the loop to end. In the case of nested loops, a numeric argument can be passed to tell the break statement how many loops to run before breaking out of the loop:

<?php

    while($i<10) {
        if($i == 7) {
            break; // Exit the while loop
        }
    }

foreach($values as $val) {
        switch($val) {
            case 'bad_value':
                break 2; // Exit the switch and the foreach
            case 'good_value':
                // Do something...
        }
    }

?>

2.6.6. switch

If a multitude of conditions exist, you can use the switch control structure to create different responses for different conditions—much as you can for an if statement. However, switch works much better in situations where you have more than one or two conditions.

A switch accepts an expression, then sets up cases. Each case is functionally equivalent to an if statement; this means that if the expression passed to the switch matches the case, then the code within the case is executed. You must separate each case with a break statement or else your code will continue to execute, producing unexpected results.

To see switch in action, you can write a quick script that determines what day it is and outputs a different response based on the result. This script uses a function called date() that allows you to format the current date (or any date, using the optional second parameter for a timestamp, which I'll cover in the next chapter).

Insert the following code into test.php:

<?php

$day = date('w'),

switch($day)
{
    case '0':
        echo "It's Sunday!";
        break;
    case '1':
        echo "It's Monday!";
        break;
    case '2':
        echo "It's Tuesday!";
        break;
    case '3':
        echo "It's Wednesday!";
        break;

case '4':
        echo "It's Thursday!";
        break;
    case '5':
        echo "Woohoo! It's Friday!";
        break;
    case '6':
        echo "It's Saturday!";
        break;
    default:
        echo "That's no day I recognize...";
        break;
}

?>

Depending on the day you run this script, you get output that follows this example when you load test.php in a browser:

It's Wednesday!

2.6.7. continue

The continue statement works similarly to break, with one essential difference: it ends only the current iteration. After a continue statement, the loop starts over at the condition evaluation.

This is useful in instances where you want to perform actions only on data in a loop that meets a certain criteria, such producing only even values:

<?php

    for($i=0; $i<=10; ++$i) {
        /*
         * If the modulus of $i and 2 is not zero (which evaluates
         * to false), we continue
         */
        if($i%2) {
            continue;
        }
        echo $i, " ";
    }

?>

Running this loop creates the following output:

0 2 4 6 8 10

2.6.8. return

The return statement in PHP is most useful in functions. When reached within a function, return immediately stops the execution of the function and passes its argument as the value of the function call. I'll cover the return statement in the section of this chapter named, "User-Defined Functions."

If you use the return statement outside of a function, the statement ends the execution of the script. Like echo and print, return is a construct of the PHP language, so no parentheses are required when you use it.

2.6.9. include, include_once, require, and require_once

A great feature provided by PHP is the ability to load a script from an external file; this makes it much easier to organize your code in larger projects.

PHP provides four constructs you can use to load an external script: include, include_once, require, and require_once.

The PHP manual recommends that developers use include_once and require_once because these constructs first check whether the file has already been loaded before either will load a given script. This saves resources and can increase the performance of your applications.

Now let's take a look at an exercise that illustrates the power of loading external scripts. Fire up Eclipse and press Ctrl+click or right-click your simple_blog project folder, hover over "New..." and select "File..." from the drop-down menu. Name the new file extras.php and add the following code to the blank document that opens:

<?php
    $foo = "green";
    $bar = "red";
?>

Save the file, then go back to our test.php file and write the following code:

<?php
    include_once 'extras.php';

    echo 'Variable $foo has a value of ', $foo, "<br />
";
    echo 'Variable $bar has a value of ', $bar, "<br />
";
?>

Save, then navigate to http://localhost/simple_blog/test.php in a browser to see the results:

Variable $foo has a value of green
Variable $bar has a value of red

By including the extras.php file you created using include_once, you are able to access the information stored in the file. This proves especially useful when you're working with a large set of functions, which allows common functions to be stored in a file that is included in other areas of your site, rather than requiring that you copy-and-paste those functions into each file. Adopting this approach reduces the size of your applications and can play a part in optimizing your application's performance.

This next short example illustrates how using include_once can reduce the load on your server; begin by adding this code toe extras.php:

<?php

$var += 1;

?>

Next, add this code to test.php:

<?php

$var = 0;

include 'extras.php';

echo $var, "<br />";

include 'extras.php';

echo $var, "<br />";

?>

This code produces the following output when loaded into a browser:

1
2

Now, change test.php so it uses include_once instead of include:

<?php

$var = 0;

include_once 'extras.php';

echo $var, "<br />";

include_once 'extras.php';

echo $var, "<br />";

?>

Next, load test.php in a browser to see the result:

1
1

The file is loaded only once, the script executes only once. This reduces the load on the server, which in turn reduces the execution time of your scripts.

2.6.10. goto

PHP 5.3.0 introduced the goto statement, which enables you to skip ahead to a new section of code:

<?php

    if ($i==7) {
        goto foo;
    }

    echo "This will be jumped if $i is equal to 7.";

    foo:
    echo "This should be printed.";

?>

NOTE

goto is a controversial addition to the language, not least because many developers feel it will have negative effects on code legibility. Also be aware that XAMPP is running PHP 5.2 by default, so goto will not work in the default testing environment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.231.15