INTRODUCTION TO PHP AND MySQL – MAKING STATEMENTS – CONTROL STRUCTURES

Control structures are used in PHP to progress the execution of the script. They may define loops within the code or be simple terms to be evaluated.

Conditional if statement

The if statement is used to perform the basic conditional PHP test to evaluate an expression for a boolean value. The statement following the evaluation will be executed only when the expression is true.

The syntax for the if statement looks like this:

if (test-expression) statement-to-execute-when-true;

The code to be executed may contain multiple statements if they are enclosed in a pair of curly brackets to form a statementblock.

In the example below the expression to be tested uses the modulusoperator to determine if the value contained in the variable called $numis exactly divisible by 2. The statement block has two statements – one to assign a string value to a variable and another to call the PHPecho() function.

  1. Create a new folder in your My PHP Sites folder called Control Structures.
  1. Create a new Dreamweaver site pointing to this folder. You will need to add Remote Info and Testing Server information, and create a new folder on the server Control Structures to which you will publish.
  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>If Statement</title>

</head>

<body>

<?php

$num = 7;

if ($num % 2 != 0 )

{

$msg = "$num is an odd number.";

echo($msg);

}

?>

</body>

</html>

Note: The example could have used ($num % 2 ! = 1) to detect an even number.

  1. Save your PHP file as if.php.
  1. Publish your file, and view the published file in a browser.

If-else statement

The PHPelse keyword can be used with an if statement to provide alternative code to execute in the event that the tested expression is found to be false.

This is known as conditionalbranching and has this syntax:

if (test-expression) do-this; else do-this;

Several expressions may be tested until a true value is found, when the code following the true expression will be executed. It is important to note that any further code contained in the if-else statement is ignored.

In the following example, any code after the call to the echo() function by the successful third test will be ignored completely.

Note: The semi-colon is required after the first code statement, before starting the else alternative code.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>If-else Statement</title>

</head>

<body>

<?php

$num = 2;

$bool=false;

if($num==1 and $bool==true)

echo("Test 1 success");

else

if($num==2 and $bool==true)

echo("Test 2 success");

else

if($num==2 and $bool==false)

echo("Test 3 success");

else

if($num==3 and $bool==false) e

echo("Test 4 success");

?>

</body>

/html>

  1. Save your PHP file as ifelse.php.
  1. Publish your file, and view the published file in a browser.

Switch statement

Conditional branching using an if-else statement can often be performed efficiently using a switch statement when the test expression evaluates the value as just one variable.

The switch statement works in an unusual way. First it evaluates a given expression, and then seeks a label to match the resulting value. The code associated with the matching label will be executed, or, if none of the labels match, the statement will execute any specified default code.

The PHPcase keyword is used to denote a label and the default keyword is used to specify the default code. All label code must be terminated by a break statement using the PHPbreak statement.

Note: Omission of the break keywords allows the execution of all other code in the switch statement.

The labels may be numbers, strings or booleans – but must all be of the same type as with this example which uses numbers.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Switch Statement</title>

</head>

<body>

<?php

$num = 2;

switch($num)

{

case 1 :

echo("This is case 1 code");

break;

case 2 :

echo("This is case 2 code");

break;

case 3 :

echo("This is case 3 code");

break;

default :

echo("This is default code");

}

?>

</body>

</html>

  1. Save your PHP file as switch.php.
  1. Publish your file, and view the published file in a browser.

For loop

The for loop is probably the most frequently used type of loop in PHP scripting and has this syntax:

For (initializer, test, increment) {statement(s)}

The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose, and it is traditional to name it $i.

On each pass of the loop an expression is tested for a boolean result and that iteration of the loop will run only if the result is true. The loop will end if the test result is false.

With each iteration the loop executes the code in the statement, then increments the counter. Multiple statements can be executed if they are contained within curly brackets to form a statement block.

Note: A for loop can count down by decrementing the counter on each iteration with $i--.

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>For Loop</title>

</head>

<body>

<?php

$a=0;

$b=0;

for( $i = 0; $i < 5; $i++ )

{

$a += 10;

$b += 5;

}

echo("At the end of the loop a=$a and b=$b");

?>

</body>

</html>

  1. Save your PHP file as forloop.php.
  1. Publish your file, and view the published file in a browser.

While loop

Another type of loop uses the PHPwhile keyword followed by an expression to be evaluated for a boolean value of true or false.

If the test expression is true then the code in the statement block will be executed. After the code has executed, the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

The statement block must feature code that will affect the test expression in order to change the evaluation result to false at some point – otherwise an infinite loop will be created.

Note: An infinite loop will lock the script so that the page will not complete.

It is important to note that if the test expression is not true when it is first evaluated, the code in the statement block is never executed.

This example decrements a variable value on each iteration of the loop, and the counter increments until it reaches 10 when the evaluation is false and the loop ends.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>While Loop</title>

</head>

<body>

<?php

$i=0;

$num=50;

while( $i<10 )

{

$num--;

$i++;

}

echo("Loop stopped at $i<br />\$num is now $num");

?>

</body>

</html>

  1. Save your PHP file as whileloop.php.
  1. Publish your file, and view the published file in a browser.

Do-while loop

The PHPdo keyword is used to denote the start of a do-while loop and is followed by a statement block containing the code to be executed on each iteration of the loop.

The statement code is followed by the PHPwhile keyword and an expression to be evaluated for a boolean value of true or false.

If the test expression is true, the loop restarts as the do keyword and will continue until the test expression becomes false.

It is important to note that, unlike the simple while loop, the statement code will always be executed at least once by the do-while loop because the test expression is not encountered until the end of the loop.

Note: A while loop is often more suitable than a do-while loop.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Do-While Loop</title>

</head>

<body>

<?php

$i = 0;

$num = 50;

do

{

$num--;

$i++;

}

while( $i<1 );

echo("Loop stopped at $i<br />\$num is now $num");

?>

</body>

</html>

  1. Save your PHP file as dowhileloop.php.
  1. Publish you file, and view the published file in a browser.

Interrupting loops

The PHPbreak keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block containing the code that the loop executes, and is preceded by a conditional test.

When the test condition is true, the break statement immediately terminates the loop and no further iterations are made.

Note: The break keyword is also used as a terminator when used with a switch statement.

Notice in the output below that the counter value is still three because the increment in the final iteration is not applied. In the following example the conditional test becomes true when the counter value reaches three.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Break Statement</title>

</head>

<body>

<?php

$i = 0;

while( $i < 6 )

{

if( $i == 3) break;

$i++;

}

echo("Loop stopped at $i by break statement");

?>

</body>

</html>

  1. Save your PHP file as break.php.
  1. Publish you file, and view the published file in a browser.

The PHPcontinue keyword is used to halt the current iteration of a loop, but it does not terminate the loop. Just like the break statement, the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test.

When the test condition is true, the continue statement immediately stops the current iteration of the loop, but further iterations will be made until the loop ends.

Note: The loop counter must be incremented before the continue condition is tested to avoid creating an infinite loop.

In the example below, the test condition is true when the counter value reaches three, so the string concatenation in that iteration is not applied but the loop continues on.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Continue Statement</title>

</head>

<body>

<?php

$i = 0;

$passes = "";

while($i < 5)

{

$i++;

if($i == 3) continue;

$passes .= "$i";

}

echo("Loop stopped at $i<br />");

echo("Completed iterations:$passes");

?>

</body>

</html>

  1. Save your PHP file as continue.php.
  1. Publish you file, and view the published file in a browser.

Return statement

The PHPreturn keyword is used in functions to return a final value to the caller of that function.

The example below contains a general purpose function called multiply() that can multiply up to five argument values and return the total to the caller.

It is called from within the echo() function to multiply three argument values. The total is returned using the return keyword, and the echo() function writes the total on the page.

Note: Each argument of the multiply() function uses a default value of 1 unless another value is passed from the caller. The example illustrated returns the number of minutes in a year, but the function call multiply(365.25, 24, 60, 60) would return the number of seconds in a year.

  1. Open a new PHP file, and enter the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<?php

function multiply($a = 1, $b = 1, $c = 1, $d = 1, $e = 1)

{

$total = $a * ($b * ($c * ($d * $e)));

return $total;

}

?>

<html xmlns="

<head>

<title>Return Statement</title>

</head>

<body>

Each year has 365¼ days<br />

Each day has 24 hours<br />

Each hour has 60 minutes<br />

Each year has <?php echo( multiply(365.25,24,60)) ?> minutes

</body>

</html>

  1. Save your PHP file as return.php.
  1. Publish you file, and view the published file in a browser.

A - Introduction to PHP and MySQL - Using your file system-Ver2.docVersion 2

Page 1 of 15