PHP Control Structures

PHP-Control-Structures-Programming-Pot
••• PHP Control Structures

In previous tutorial we learned about the PHP Operators and low in this tutorial we learn about the PHP Control Structures. Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.

  1. if
  2. else
  3. elseif/else…if
  4. while
  5. do-while
  6. for
  7. foreach
  8. break
  9. continue
  10. switch
  11. declare
  12. return
  13. require
  14. include
  15. require_once
  16. include_once
  17. goto

PHP Control Structures


PHP Control Structures

1) if


The if PHP Control Structures is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if a structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, an expression is evaluated to its Boolean value. If the expression evaluates to,TRUE PHP will execute a statement, and if it evaluates to FALSE – it’ll ignore it. More information about what values evaluate to can FALSE be found in the ‘Converting to boolean’ section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
  echo "a is bigger than b";
?>

2) else


The else PHP Control Structures is only executed if the if expression evaluated to, FALSE and if there were any elseif expressions – only if they evaluated to FALSE as well.

Often you’d want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case of the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a > $b) {
  echo "a is greater than b";
} else {
  echo "a is NOT greater than b";
}
?>

3) elseif/else…if


The elseif PHP Control Structures is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

4) while


while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

It is also one of the most important PHP Control Structures.

4) do-while


do-while loops are very similar to while loops, except the truth expression, is checked at the end of each iteration instead of in the beginning.

There is just one syntax for do-while loops:

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

The above loop would run one time exactly since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

5) for


for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

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

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}
?>

6) foreach


The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).

The second form will additionally assign the current element’s key to the $key variable on each iteration.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

This is very important PHP Control Structures.

7) break


A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement.

<?php
echo "hello";
if (true) break;
echo " world";
?>

will only show "hello"

8) continue


continue is used within looping PHP Control Statements to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

9) switch


The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

switch structure allows usage of strings:

<?php
switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}
?>

10) declare


The declare construct is used to set execution directives for a block of code. The syntax of declaring is similar to the syntax of other flow control constructs:

declare (directive)
    statement

As directives are handled as the file is being compiled, only literals may be given as directive values. Variables and constants cannot be used. To illustrate:

<?php
// This is valid:
declare(ticks=1);

// This is invalid:
const TICK_VALUE = 1;
declare(ticks=TICK_VALUE);
?>

11) return


return returns program control to the calling module. Execution resumes at the expression following the called module’s invocation.

If called from within a function, the return statement immediately ends execution of the current function and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.

look at that example:

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
return;
?>

(executing a.php:) will echo "ba".

whereas (b.php modified):

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
exit;
?>

(executing a.php:) will echo "b".

12) require


require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

<?php
require 'somefile.php';
?>

13) include


Include files can make sites easier to manage. For example, you can create a piece of content such as a page banner, site information block, or menu that you want to include on multiple pages in your site. When you want to change the content, you can make the change in a single file, and the change will be reflected on every page in which the include file appears.

A PHP include statement is a code block that pulls content from an external file into a web page. The following is an example of a PHP include statement:

<?php
 include('pageBanner.php');
 ?>

14) require_once


The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once documentation for information about the _once behavior, and how it differs from its non _once siblings.

<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/config.php');
?>

15) include_once


.The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns .TRUE As the name suggests, the file will be included just once.

<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again! (PHP 4 only)
?>

16) goto


This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

<?php
goto a;
echo 'Foo';
 
a:
echo 'Bar';
?>