An Introduction to PHP

Programming Constructs

Structured programming is based around three basic constructs: Sequence, Selection and Iteration. The Sequence construct is the simplest, whereby statements are executed in the order they're found in the code.

Both the Selection and Iteration constructs require a Logical Test. Logical tests can be performed on variables, literal values, calculations, and results of functions The test will evaluate to either true or false.

Selection Constructs

The Selection constructs are used when the flow of execution may flow down two or more paths.

The if Statement

The if statement is used to control the flow of execution down one of two or more paths, depending on the result of a logical test. Further conditions may be specified with else if, should previous conditions be false, and else may be used should none of the above be true. There is no semicolon at the end of an if statement.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Simple if Statement</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    $morning = date("I");
    if ($morning == "1")
        print "Good morning <br>";
    else
        print "Good afternoon <br>";
?>
</p>
</body>
</html>

If statements can be nested, and the combined with logical operators.

If more than one line should be executed should a condition be True, the lines should be enclosed within curly braces.

if ($x == 10)
{
    print "That's an excellent result <br>";
    print "You should be extremely proud of yourself! <br>";
}

Note: A common mistake is to use the assignment operator instead of the equality operator when checking for equivalence. The following statement will always evaluate to True as x is assigned the value 10 which is a non-zero number.

if ($x = 10)

The switch Statement

When there are many conditions, the switch statement can be used if the values are discrete. The switch statement is easier to read than multiple if statements when there are a large number of discrete values.

The switch statement can be used when multiple if statements become messy and difficult to read. Each case statement is an entry point, and execution will continue from that point unless a break statement is found. The break statement causes the program to continue from the end of the switch statement. Only discrete values may be used for the cases. The default statement is used if none of the listed cases are True. There is no semicolon at the end of the switch statement.

The following example prints the word for the numbers 1 to 10 passed from a form to the PHP script.

simpleForm.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Basic Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Number Converter</h1>
<form id="selection" name="selection" method="post" action="printNumber.php">
<p>
    <input type="text" size="5" value="" name="numWord"><br>
    <input type="submit" value="Display Word" name="convert">
</p>
</form>
</body>
</html>

The following is the PHP script that is called from, simpleForm.html.

printNumber.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Number to Word</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    switch ($numWord)
    {
    case 1:
        print "One <br>";
        break;
    case 2:
        print "Two <br>";
        break;
    case 3:
        print "Three <br>";
        break;
    case 4:
        print "Four <br>";
        break;
    case 5:
        print "Five <br>";
        break;
    case 6:
        print "Six <br>";
        break;
    case 7:
        print "Seven <br>";
        break;
    case 8:
        print "Eight <br>";
        break;
    case 9:
        print "Nine <br>";
        break;
    case 10:
        print "Ten <br>";
        break;
    default
        print "Number not between 1 and 10 <br>";
    }
?>
</p>
</body>
</html>

Iteration Constructs

The Iteration constructs are used when a block of code is required to be executed continually until a condition is met.

Pre-Condition Loops

Pre-condition loops allow for a condition to be tested at the start of the loop. This type of loop is used when you only want to execute the block of code should the condition be true. If there is more than one line to be included in the iteration, it should be contained within curly braces.

A semicolon is not added to the end of the while statement. If one is added in error, then the block of code will be executed exactly once.The following example uses a pre-condition loop to calculate the factorial of a number (a number that is multiplied by every integer number below itself down to 1).

simpleForm.html

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Basic Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Factorials</h1>
<form id="selection" name="selection" method="post" action="printFactorial.php">
<p>
    <input type="text" size="5" value="" name="num"><br>
    <input type="submit" value="Display Factorial" name="convert">
</p>
</form>
</body>
</html>

The following is the PHP script that is called from, simpleForm.html.

printFactorial.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Factorial</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    $factorial = 1;
    // Use a pre-condition loop to calculate the factorial
    while ($num > 1)
        $factorial *= $num--;
    print "Factorial: " . $factorial;
?>
</p>
</body>
</html>

Post-Condition Loops

Post-condition loops allow for a condition to be tested at the end of the loop. This type of loop is used when you want to execute the block of code at least once. If there is more than one line to be included in the iteration, it should be contained within curly braces. The following example increments the value of result at least once, and continues incrementing result while it has a value less than 10.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Post Condition Loop</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    $result = 1;
    /*
        Use a post-condition loop to increment the result and
        continue incrementing the result while it has a
        value less than 10
    */
    do
    {
        $result++;
        print $result . "<br>";
    }
    while ($result < 10);
?>
</p>
</body>
</html>

Counted Loops

Counted loops are used when you know how many times you want to execute a statement or a list of statements. A semicolon is not added to the end of the for statement. If one is added in error, then the block of code will be executed exactly once. The general syntax for a counted loop is:

for (initialisation_section; condition; increment_section)
{
    // List of statements
}

The parameters that the counted loop operates on are in three sections separated by semicolons. The first section is for initialising any variables, the second section has the condition, and the third section has any increments required to implement the loop. If more than one variable is to be used in either the initialisation_section or the increment_section, then they are separated by commas. The condition must evaluate to either true or false. Compounded conditions must be created by using the logical operators. The following example uses a counted loop passed from a form, and prints the prime numbers (a number divisible only by itself and 1) between 1 and a number enetered by the user.

simpleForm.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Basic Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Prime Numbers</h1>
<form id="selection" name="selection" method="post" action="displayPrimes.php">
<p>
    <input type="text" size="5" value="" name="num"><br>
    <input type="submit" value="Display Prime Numbers" name="dispPrimes">
</p>
</form>
</body>
</html>

The following is the PHP script that is called from, simpleForm.html.

displayPrimes.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Prime Numbers</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    print "The following are the prime numbers from 1 to " . $num . "<br>";
    for ($counter=1; $counter < $num; $counter++)
    {
        $test = $counter;
        $prime = 1;
        while ($test-- > 2)
            if (($counter % $test) == 0)
                $prime = 0;
        if ($prime == 1)
            print $counter . " is a prime number <br>";
    }
?>
</p>
</body>
</html>

The foreach Construct

Arrays in PHP are associative. PHP provides a foreach construct to iterate through an associative array in terms of the key/value pair in the array. The keyword as is used to place the key/value pairs into the special $key=>$value syntax. The following example illustrates how to use the foreach construct to iterate through the $GLOBAL array, a PHP array that is used to store the global variables that your script can access.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Global Array</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Global Array</h1>
<p>
<?php
    foreach($GLOBALS as $key=>$value)
        print $key . " = " . $value . "<br>";
?>
</p>
</body>
</html>

You might also like...

Comments

About the author

Gez Lemon United Kingdom

I'm available for contract work. Please visit Juicify for details.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Linux is only free if your time has no value” - Jamie Zawinski