Library tutorials & articles

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>

Comments

  1. 28 May 2009 at 22:12

    It is not just talk though: Zend server is flourishing despite the recession - "the Q1 of 2009 has been our strongest quarter ever," says Suraski - and although PHP's enterprise market share is small compared to Java or .NET, it is growing. Read more on ITJOBLOG.

  2. 02 Jan 2007 at 06:39
    Here they show how to send valued in one file to another(both are in same folder)
    but i need to send values in one folder to another


  3. 04 Apr 2006 at 10:20

    Yes, I think you're correct, although you could easily have a line like this:

    $num = $_POST['num'];


    to get around that problem. Which I think is what's missing from this tutorial Wink [;)]





  4. 04 Apr 2006 at 09:47

    In the PHP file should it be "$_POST["num"]" ?

    instead of just $num?

  5. 21 Feb 2004 at 04:09
    hello

    I have in php a header which brings a save as box , but when file is down loaded it contains the 6 blank spaces at the start of of document .
    I have to avoid storing these blank spaces.Please help me to solve this problem.
  6. 28 Jan 2004 at 15:16

    You can also do string concatenation like

    Code:

    $h = "Hello";
    $w = "World";


    $message = "$h $w";


  7. 01 Jan 1999 at 00:00

    This thread is for discussions of An Introduction to PHP.

Leave a comment

Sign in or Join us (it's free).

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

Related discussion

Related podcasts

  • EarthClassMail.com - Moving from LAMP to .NET 3.5

    Scott chats with Matt Davis, architect at EarthClassMail.com, about their move from a LAMP stack (Linux/Apache/mysql/PHP) to .NET 3.5. What's working, what's not, and what kinds of issues are they running into as their architect their solution.

Events coming up

  • Dec 3

    The Auckland PHP December meetup

    Auckland, New Zealand

    Topic: Magento E-Commerce platform Speaker: Robert Popovic, LERO9, Robert is the Technical Director and co-founder of LERO9. Robert attended the Electrotechnical Faculty at The University of Belgrade where he graduated with a Masters in Computer Science and Information Technology. Robert has worked exclusively in the field of web and software development throughout his career.

We'd love to hear what you think! Submit ideas or give us feedback