25
PHP Workbook Brendan Riordan & Matthew Green - Page 1 of 25 PHP WORKBOOK Brendan Riordan Matthew Green School of Computing and IT University of Wolverhampton

Php Work Book

Embed Size (px)

DESCRIPTION

Php Work Book

Citation preview

Page 1: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 1 of 25

PHP WORKBOOK

Brendan Riordan Matthew Green

School of Computing and IT

University of Wolverhampton

Page 2: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 2 of 25

Chapter 1

What is PHP ? “Self- referentially short for PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.” –Webopedia What does this mean ? Open Source – the source code is generally available to the public, who may update or modify it. Generally, the production of the code is a collaborative venture between programmers, and is a response to proprietary code produced by corporations such as Microsoft. The software is, therefore, FREE. Server-Side – in a client-server model, such as the Web, the scripts are run on the Web Server and not the client’s PC. This is in contrast to JavaScript, which is executed on the client’s PC. Dynamic Web Pages – are pages which can change every time a client access them (changes may be due to the client’s location, the time of day, profile of the viewer etc). In this case Dynamic Web Pages means HTML extensions that will enable a Web page to react to user input without sending requests to the Web server. PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3). At the time of writing (Jan 2003) the latest version is 4.3.0. PHP scripts are embedded within HTML code, and is differentiated from the HTML by the use of tags, eg <html> <?php php code goes here; ?> </html> The <?php tag indicates where the PHP code begins, and the ?> tag indicates where it ends. Note that you can either use <?php …?> or you can use <? …?>. The longer tag <?php avoids confusion with processing instructions that can be used with HTML and so is used throughout this work book. The main purpose of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP. PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases, such as MySQL. The home of PHP is at www.php.net Here you will find updates, the on-line manual, tutorials, utilities, examples of code, discussions etc A good book on PHP and MySQL is “Web Database Applications with PHP & MySQL”, Hugh E.Williams & David Lane, O’Reilly (2002), 9-780596-000417

Page 3: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 3 of 25

How do I get started ? You will need to either identify a web server which supports PHP, and upload your scripts to it, or to run some web server software on your PC to test your scripts. A web server is available in SCIT which supports both PHP and MySQL, the URL is http://www.clun.scit.wlv.ac.uk Any PHP scripts you wish to execute/test should be place in your user area on this server. Scripts may uploaded using the FTP software provided in the “Windows Comms” folder on all University PCs. If you want to run PHP on your machine at home, please note the following:

• You will need to install some Web Server software, before you can install and run PHP

• The usual choice for home users is Microsoft’s “Personal Web Server” which is on the Windows CD.

• Microsoft’s PWS does not run on Windows XP (Home Edition), although it does with Windows XP (Professional Edition). It is suggested that if you are running Windows XP (Professional Edition), IIS should be installed – ‘Start’, ‘Control Panel’, ‘Add or Remove Programs’, ‘Add/Remove Windows Components’, ‘Internet Information Services IIS’

• If you are not running Windows XP (Professional Edition), you are advised to install PHPTriad. This is piece of freeware, which will install Apache for Windows 1.3, PHP 4.0, MySQL 3.23 and Perl. It takes less than five minutes to have all the software up and running, and requires you only to use the “winmysqladmin” software to set yourself up an account in MySQL. The software may be downloaded from Brendan Riordan’s web site at www.scit.wlv.ac.uk/Brendan

• Whilst PHP Triad is easy to install, support is beyond the scope of this work book. If in doubt, use a PHP-enabled web sever – such as www.clun.scit.wlv.ac.uk.

• Details on installing PHP manually within a Windows environment, can be downloaded form the local version of the on- line manual at http://www.scit.wlv.ac.uk/appdocs/php/install.windows.html

How do I create a PHP page ? As with HTML, the best way to learn is not to use a web development package such as FrontPage, but to write all your code ‘by hand’. Therefore, the best development tool is Notepad. However, for these workshops you may use a tool such as PHP Edit version 0.6 (www.phedit.net), which offers limited help with PHP syntax. Do not download version 0.7 as the author himself describes it as ‘unstable’. Note: The CHM version of the PHP Manual may be downloaded from www.php.net and integrated in to the Help section of PHP Edit. Details are available from http://help.phpedit.net/en/module.HelpIntegration.php NB – If you decide to use Notepad to edit your scripts, you must add the “.php” extension when you do a “Save As ..”. Failure to do this will mean that Notepad will add a “.txt” file extension by default. Therefore, if you want to save a PHP file with the name of “index”, select “File”, “Save As …”, and enter the name “index.php”. Be aware that any code you submit for assessment will be subject to a ‘viva’ with your tutor, during which you must give a full explanation of the code, demonstrating a clear understanding, and leaving in no doubt that you are the author of the original code.

Page 4: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 4 of 25

Chapter 2

Note – You are encouraged to type up all the examples given in this, and subsequent chapters, and test them on a pHP-enabled server. You will learn a great deal by having to

test and de-bug your software.

Instructions Instructions are separated the same as in C, Pascal or Perl - terminate each statement with a semicolon. The closing tag (?>) also implies the end of the statement, so the following are equivalent:

<?php echo "This is a test"; ?>

<?php echo "This is a test" ?> You would normally expect to see PHP embedded within an HTML page, such as in the following example <html> <head> <title>Hello World – My First PHP Page</title> </head> <body bgcolor=”#ffffff”> <h1> // A Simple output statement <?php echo “Hello World”; ?> </h1> </body </html>

In the example above note:

• PHP is embedded within HTML code, differentiated by the PHP tags. • The PHP script is within a HTML <h1> tag, formatting the PHP output. • When a PHP script is run, the entire script is replaced by the output of the script

being run on the server. • A comment has been placed after //

Page 5: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 5 of 25

Output It is good practice to comment your code. It clarifies the meaning of your code, allows easier de-bugging, and if you ever inherit code that you must work with you will appreciate it if the author has left comments explaining some of the more obscure algorithms used. There are three forms of syntax for the comment command: // This a single line comment # This is also a single line comment /* This shows how you can break a comment over several lines */

You may use any of the three forms of comment syntax, but this handbook will largely use the first type, ie // comment …. The command to send output to the screen is either the ‘echo’ command or ‘print’ command. Whilst they are fundamentally very similar, there are subtle differences between these two commands. echo “hello”; // is exactly the same command as echo (“hello”);

Note: if you use parentheses with the ‘echo’ command, only one output parameter may be used. However, they make no difference to the ‘print’ command.

String Literals It is possible to use either single quotation marks, or double quotation marks, ie echo ‘These quotation marks work”; echo ‘and so do these’;

Clearly there can be problems when you include quotation marks within the string itself. For example, supposing you want to display the text:

Page 6: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 6 of 25

The student said “PHP is easy to learn”, and continued with his work. If we used an ‘echo’ command with these quotes, he PHP interpreter would get very confused as to when the string began, and when it ended, ie

echo “The student said “PHP is easy to learn”, and continued with his work.”;

Start Printing Stop Printing Start Printing Stop Printing To avoid this confusion, the following syntax must be used when using quotation marks within strings; // these strings contain quotation marks echo “ This string has a ‘ a single quote! ”; echo ‘ This string has a “ a double quote! ’;

The quotation marks can be escaped using: echo " This string has a \" double quote! "; echo ' This string has a \' single quote! ';

If you have tried any of the above examples, and you should have !, you will find that consecutive ‘echo’ commands produces output on the same line, ie the code above produces the following on screen:

This string has a " double quote!This string has a ' single quote! If you wish to start output on a new line you must put a line break where required. Note that the <br> tag is used (as in HTML), but the tag must be placed within the string. This is demonstrated in the example below: echo "This line is immediately followed"; echo "by this line - no breaks !<br>"; echo "However, this is on a new line<br>"; echo "and so is this !";

Produces on screen:

This line is immediately followedby this line - no breaks ! However, this is on a new line and so is this !

Page 7: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 7 of 25

Print Statement The ‘print’ statement is usually used to output the value of variables (more on these later), calculations, data from a database etc A simple example would be as follows echo "The value of 8 plus 4 is "; print(8 + 4); print "<br>"; echo "The value of 8 minus 4 is "; print (8 - 4); print "<br>"; echo "The value of 8 times 4 is "; print (8 * 4); print "<br>"; echo "The value of 8 divided by 4 is "; print (8 / 4);

The output is:

The value of 8 plus 4 is 12 The value of 8 minus 4 is 4 The value of 8 times 4 is 32 The value of 8 divided by 4 is 2

Note the use of the print”<br>”; statement. What does it do ? (Hint: re-read the previous page) Other tags may be embedded within a ‘print’ statement, in order to format text. Common tags, with which you are familiar with from HTML, include: echo "This word is <strong> bold </strong>,"; echo "this word is in <em>italics</em> "; echo "and this word is <strong><em>both</em></strong>";

Produces:

This word is bold ,this word is in italics and this word is both Try the following, more complex example:

print("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to my website.</font>");

Page 8: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 8 of 25

Chapter 3

Variables A variable is a place in the computer’s memory where you can store some data. The stored value can change, and is often as the result of some calculation or processing having taken place. A variable in PHP is identified by the first character being a dollar sign, ‘$’. Variables do not have to be declared before using them, and they have no value until assigned one. The process of assigning a value to the variable also defines what type of variable it is, e.g. text or numeric. This process of implicitly defining a variable means that if the value is changed, then it can be implicitly re-defined. The following line of code shows a variable called $num, and assigns it a value of 17. This implicitly defines it as an integer (whole number).

$num = 17; To re-define this variable, so it contains text (a string of characters), we use the following code:

$num = “University of Wolverhampton” Note, that this would not be a meaningful name for this variable. Perhaps a more meaningful name might be $university. The process of re-defining variables can both be flexible and dangerous, if not used with some care. Look at the following example which uses both a string and an integer variable. $students = 34; $module = "CP1058"; echo "The class $module has $students enrolled on it";

This produces:

The class CP1058 has 34 enrolled on it NB – A common error is to use an undefined variable in an expression.

Types of Variable There are four type of scalar (can contain a single value at any given time) variable supported by PHP. These are:

• Boolean • Float • Integer • String

Page 9: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 9 of 25

PHP also supports compound types (array or object). These can contain a number of scalar values, such as the days of the week, the scores of students in an exam etc. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. The underscore is used instead of a space (not permitted in PHP). For example, if you chose the variable name ‘$my age’ it would not be permitted. The variable ‘$my_name’ would be. Boolean – these are very simple variables, in that they can only hold the values true or false. They are often used to determine what action should be taken - according to their value. // These are Booleans $jackpot = false; $male = true; Integer – A whole number, sometimes known as a counting number. Note, these can be positive or negative, e.g. -37, 5, 4732, -162, 0, 56 // This is an integer $distance = 42;

Float – A number which has a fractional part. Note this may be a decimal, or represented in exponential notation (scientific format). // This is a float $distance = 42.0; // This is a float equal to 1120 $num = 1.12e3; //This is a float equal to 0.02 $num = 2e-2;

String – We have already seen numerous examples of string variables on previous pages. A string can contain a single character, or numerous characters. $initial = “B”; $surname = “Riordan”;

Page 10: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 10 of 25

Constants If variables are values which may ‘vary’ during the life of a script, then a constant is a value which remains ‘constant’ (does not vary) during the life of that script. Therefore, it is assigned a value which is used throughout the script. Examples would be the number of hours in a day, the number of students on a course, the rate of VAT etc. Define (“pi”, 3.142); // output the value of twice pi print (2 * pi);

This produces:

6.284 Note the syntax of the definition of pi, and the fact that unlike variables, constants do not have a ‘$’ as their first character. Constants are much underused by new programmers. If used to define the number of lines used on a web page, it can be altered once, without having to make numerous changes throughout the code.

Expressions, Operators and Variable Assignments Some of examples of assigning a variable the value of an expression by using an equals sign, e.g. Assignment

$total = $first + $second + $third; Variable Expression Exercise 1 – type the following code as part of a web page. Insert your own ‘echo’ or ‘print’ statements to output the various values to screen once they have been calculated. Check that the output to screen is what you were expecting (check your answers; ensure there are sufficient line breaks to produce a neat output). $num = 1 $num = 4 +9; // all the following add one to the value of $num $num = $num + 1; $num += 1; $num++; // all these subtract on from $num $num = $num -1;

Page 11: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 11 of 25

$num -= 1; $num--; $num = 23; // double the value of $num $num = $num * 2; $num *= 2; $num = 100; // halve the value of $num $num = $num / 2; $num /= 2; $num = 8; // A combination $num = ((($num + 4) * 2) - 6) / 3);

Exercise 2 – Write a PHP script which assigns the first three prime numbers to the variables $prime1, $prime2 and $prime3. Two calculations should determine the total (addition) of these three numbers, and the sum (multiplication) of the three numbers. Suitable lines of code should output the results in this type of manner:

The total of <first number> + <second number> + <third number> = <answer> PHP contains a library of mathematical functions which are available to you. These are well documented elsewhere, and you are encouraged to research this topic.

Operator Precedence When a mixed expression is presented to the PHP interpreter, the order in which the calculation is to be performed must be determined - unless parentheses (brackets) clarify the intended order. Without parentheses the expression is evaluated according to the ‘oder of precedence’ – which amongst other things states that multiplication and division occur before addition and subtraction). For example, what is the value of $num when this expression has been evaluated:

$num = 2 * 3 + 4; Is it 10 ? (2 times three is six, plus 4 is 10). Is it 14 ? ( twice 7 – the three plus 4) The rules of precedence can be confusing at first. Therefore it is strongly suggested that you use parentheses, eg // this produces an answer of 10 $num = (2 * 3) + 4; //this produces an answer of 14

Page 12: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 12 of 25

$num = 2 * (3 + 4);

Type Conversion At times you may wish to convert a variable from one type to another. An example might be if someone’s age is stored as “23”. This is a string of characters. If you wanted to do any calculations with it, you will have to convert it in to an Integer. PHP offers functions that do this for you, as well as some automatic type conversion. Functions - A string variable = strval(a mixed variable) An integer variable = intval(a mixed variable) A float variable = floatval(a mixed variable) eg if a variable called $age contains the string value “23”, and you want to calculate how many years there are before that person reaches 40, the code would use the second of the listed functions above, e.g. // assigns the string value to $age $age = "23"; //convert the string to an Integer $int_age = intval($age); $years_to_go = 40 - $int_age; echo("The years to go before forty is $years_to_go");

This produces:

The years to go before forty is 17 Automatic Type Conversion – This occurs when variables of two or more types are mixed in an expression, with one of the variables being used as though it were of a different type. Under these circumstances, PHP will automatically convert the variable. The conversion follows set built- in rules, therefore it is best to ensure that you have clarity in all expressions you write, or that you write code to do the conversion for you. Type the following PHP code in to a web page. Predict what you think the output will be, and insert appropriate ‘print’ or ‘echo’ statements to display the results on your page. Be careful, the second three type conversions are not so obvious. // $num is set as an integer = 115 $num = “100” + 15; // $num is set as a float = 115.5 $num = “100” + 15.5; // $title is set as a string = “39 steps” $title = 39 . “ steps”;

Page 13: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 13 of 25

// $num is set as an integer = 39 $num = 39 + “ steps”; // $num is an integer = 42 $num = 40 + “2 blind mice”; // $num is a float, but what does it mean ? $num = “test” * 4 + 3.14159;

Ensure you put some line breaks in to your code – to improve appearance. The code produces:

115 115.5 39 steps 39 42 3.14159

Exercise 3 – Create a number of variables, assigning them with your personal details, as though these had been entered on a form – name, various fields of your address, post code, phone number, etc. Using a web page, and as much PHP as possible, output these details, using appropriate text formatting.

Page 14: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 14 of 25

Chapter 4 Decisions, Decisions So far, we learnt to write some simple PHP code, the main feature of which is that every line of code is executed. At times you may wish code to be executed only if certain conditions apply. ‘If’ statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed. Sounds complicated ? – It’s not. For example, if today is a weekday get up and go to University, else stay in bed. This can be generally represented by: IF (today = a weekday) [1] Go to University [2] Else Stay in bed [3] [1] The test which is evaluated [2] The action to be carried out if the test evaluates as True [3] The action to be carried out if the test evaluates as False Note – You may require that several lines are executed, rather than a single statement. In this case we use ‘braces’ or curly brackets. This is shown as follows: if ($num > 10) { statement; statement; statement; } else { statement; statement; } Note how the braces delineate the two blocks of code, the use of brackets in the IF statement, and the semi-colons to mark the end of each of the five statements. IF and Variables One of the most common uses of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example: if ($username == "webmaster") which would compare the contents of the variable $username to see if it is exactly (hence the two equals signs) the same as “webmaster”. If it is the ‘then’ section of code will be

Page 15: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 15 of 25

executed. Exactly equal to means that if $username contained “Webmaster” or “WEBMASTER” the test would evaluate as false. Constructing The THEN Statment To add to your script, you can now add a THEN statement: if ($username == "webmaster") {

echo "Please enter your password below"; } This will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements. Constructing The ELSE Statement Adding The ELSE statement is as easy as the THEN statement. Just add some extra code: if ($username == "webmaster") {

echo "Please enter your password below"; } else {

echo "We are sorry but you are not a recognised user"; } Of course, you are not limited to just one line of code. You can add any PHP commands in between the braces. You can even include other IF statements (nested statements).

Other Comparisons There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g. if ($enteredpass == $password) You can also use the standard comparison symbols to check to see if one variable is greater than or less than another: if ($age < "13") Or : if ($date > $finished) You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:

Page 16: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 16 of 25

if ($name == "" || $email == "" || $password == "") {

echo "Please fill in all the fields"; }

ELSEIF If a number of consecutive IF statements are required, these may be linked using the’elseif’ statement. The two boxes below show firstly, linked If, Then, Else statements, and secondly the same functionality using ElseIf statements. if ($num < 5) echo “Number is very small”; else if ($num < 10 ) echo “Number is small”; else if ($num < 20) echo “Number is big”; else if $num < 30) echo “Number is very big”;

if ($num < 5) echo “Number is very small”; elseif ($num < 10 ) echo “Number is small”; elseif ($num < 20) echo “Number is big”; elseif $num < 30) echo “Number is very big”;

A programmer has the choice of using either format, however if these become unduly lengthy then they are best replaced with the ‘Switch’ statement.

Switch Statement The ‘switch’ statement is a more compact, readable and efficient form of dealing with multiple ‘If’ conditions. It is much easier to read, and de-bug. It is ideal for when an option has to be chosen from a list of choices. The following code shows how the user has made a choice, which has been stored in the variable $menu, and the code then selects what form of action is necessary – according to the user’s choice. In this case it merely repeats back the user’s choice.

Page 17: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 17 of 25

Switch ($menu) { case 1: echo “You chose number one.”; break; case 2: echo “You picked number two.”; break; case 3: echo “You picked number three.”; break; case 4: echo “You picked number four.”; break; default: echo “You picked another option”; }

Note the following features: the braces which show the start and finish of this construct, the use of the ‘break’ statement (this ensures that only one of the options is executed, by finding a matching option and breaking out of the ‘switch’ construct at that point, the use of semi-colons and the fact that more than one statement can be executed.

Conditional Expressions Thus far, we have used the equals sign t see if two expressions are the same, or the double equals sign to test if both sides are identical (including the case of the letters in a string). There are conditional comparisons which can be used, particularly with the ‘If’ statement. We can use the inequality operator to test if a variable is not equal to an expression. Consider this code: $num = 0; if ($num != 1) echo “Does not equal one 1”;

The expression evaluates to be True (1 does not equal 0), and therefore the ‘echo’ statement is executed. It may also be necessary to evaluate whether or not two conditions both hold true, or if one of two conditions hold true. If we wish to evaluate that both conditions are true we use ‘AND’, if only one or the other needs to be true we use ‘OR’. This is best shown in the following examples:

Page 18: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 18 of 25

Condition A – Is it a Weekday ? Condition B – Is it good weather ? Result – If A and B are both True, walk to work Result – If either A or B are not True , then think about it

Is it a weekday ? Is it good weather ? Description Result

True True It is a weekday, the weather is good Walk to work

True False It is a weekday, but the weather is bad

Think about it

False True It is not a weekday, the weather is good Think about it

False False It is not a weekday, the weather is bad

Think about it

This could be represented by the following code, which uses two Boolean variables ‘$weekday’ and ‘$good_weather’ // Note that Booleans hold the value true or false, not the strings ‘true’ or ‘false’ $weekday = true; $good_weather = false; if ($weekday = true) && ($good_weather = true) echo “It is a nice day, why not walk to work ?”; else echo “Think about it !”;

If the above were to be evaluate, you would not walk to work since you need both conditions to be true. In this example it is a weekday, but the weather is not good. The && symbol means ‘AND’ so the ‘If’ statement can be paraphrased as “If it is a weekday, and the weather is good, then walk to work, else think about it.” The other common conditional operator is ‘OR’. This is used when only one condition or the other needs to be true, for the statement to be executed. Using the example above leads to some interesting results, as is shown: Condition A – Is it a Weekday ? Condition B – Is it good weather ? Result – If A or B are True, walk to work Result – If both A and B are not True , then think about it

Is it a weekday ? Is it good weather ? Description Result

True True It is a weekday, the weather is good Walk to work

True False It is a weekday, but the weather is bad Walk to work

False True It is not a weekday, the weather is good Walk to work

False False It is not a weekday, the weather is bad

Think about it

Page 19: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 19 of 25

Note in this example we will walk to work at weekends (Is it a weekday = False), because the weather is nice. Remember if only one or the other of the conditions are true it evaluates overall as true. The code for this is as follows: // Note that Booleans hold the value true or false, not the strings ‘true’ or ‘false’ $weekday = true; $good_weather = false; if ($weekday = true) ¦¦ ($good_weather = true) echo “It is a nice day, why not walk to work ?”; else echo “Think about it !”;

In the code above the symbol ‘¦¦’ represents ‘OR’.

Mathematical Comparisons We have already seen the use of ‘=’ and the use of ‘= =’. PHP version 4 introduced a new comparison that is not implemented in any other programming language. The comparison is ‘= = =’, and it means the expression evaluates as being equal and the arguments are of the same type . The other normal mathematical operators apply, and are summarised below.

= Equal to >= Greater than or equal to = = Exactly equal <= Less than or equal to

= = = Exactly equal, same type > Greater than != Not equal to < Less than

Unary Not Operator Any of the Boolean expressions you have seen so far can be negated with the unary not operator. If an expression evaluates to be True, and we negate it, it becomes false, and vice versa. For example: $num = 1; echo “variable = 1” $num != 1; echo “variable is NOT equal to one”; !$num !=1; echo “variable IS equal to one;

Page 20: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 20 of 25

Exercise 1 – Assign a value to a variable called $num. Write an ‘If’ statement to determine if the number is even or not, and display an appropriate message. Exercise 2 – Assign values to two variables called $num1 and $num2. If $num1 is greater than $num2 then display the message “The first number is larger”, otherwise display the message “The second number is larger”. Exercise 3 – Adapt the last exercise to deal with the occasion when both numbers are equal to each other. Exercise 4 –Assign a value (in the range 1900 to 1999) to a variable called $year. Using a ‘Switch’ statement, determine which decade the year fell in and output an appropriate message, eg “The year was in the noughties”, “The year was in the tens”, “The year was in the twenties” etc Exercise 5 - Declare a constant string value called password with the value ‘wolf’. A second variable called $guess should contain a string of your own choosing. Determine if the two stings are:

• Not the Same • The Same • Exactly the Same

and output the appropriate message to screen. Change the value of $guess to test all options.

Page 21: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 21 of 25

Chapter 5

I Feel Like I Am Going Around in Circles So far, we have seen how to write sections of code where every line is executed, and where conditional statements determine which lines of code are executed using ‘If’ and ‘Switch’. However, both type of code run from top to bottom and cease execution. Any ‘real’ application often requires that sections of code are repeated either a given number of times, or until certain criteria have been met. PHP supports four different types of loop structures:

• while • do … while • for • foreach

The first three type of loop are general purpose, and familiar to programmers in most languages, the last is specific to arrays.

While This is probably the simplest loop structure to use. The loop continues to execute one or more instructions, whilst a condition remains true. The condition is checked first, and if found to be true the loop is executed while the condition remains true. If at the first check the condition is found to be false, the loop is never executed at all. It is essential that within the body of the loop a statement is capable of making the condition false. Without this, the loop will never cease to loop – an infinite loop. This is a common error when first writing loop structures in your code. The following code prints the integers from 1 to 10 to screen, with a space between each. $count = 1; while ($count < 11) { echo $count; echo “ “; // increment the value of $count $count = $count + 1; }

Note – the value of $count is given an initial value (1) outside the loop, the condition for the loop is while $count has a value of less than 11, within the body of the loop a statement changes the value of $count – so that eventually the ‘While’ condition is no longer true and the loop ceases execution.

Page 22: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 22 of 25

Do While … The fundamental difference between this and the While loop concerns where in the process the condition is evaluated.

• In a ‘While’ loop the condition is evaluated at the start of the loop, and if found not to be true the loop will not execute at all. Therefore, a ‘while’ loop may execute a number of times, or may not execute at all.

• In a ‘Do While …’ loop the statement which evaluates whether the loop needs to execute again is at the bottom of the block of code being executed. Therefore, this loop will execute at least once.

The following loop has the same functionality as the ‘While’ loop. Examine the code and see the difference. $count = 1; do { echo $count; echo “ “; $count = $count + 1; } While ($count <11);

What is the output from the following loop ? $count = 1000; do { echo $count; echo “ “; $count = $count + 1; } While ($count <11);

This produces the number 1000, as the body of the loop is executed once, the condition fails (1000 is not less than 11), and the loop stops executing. This structure is the same as ‘Repeat Until …’ found in many programming languages, and is not frequently used as it is unusual to have loop execute once even if a condition is false.

For The syntax for this loop is the most complex, but it produces very tight code. The syntax is described below:

for(initial statement; condition for the loop; end- loop condition)

Page 23: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 23 of 25

Note that there are three sections, each separated by a semi-colon. To make things more complex, each of the three parts is optional. If we write the same structure as used in the last two types of loops in the form of a ‘For’ loop, the code is: for($count=1; $count<11; $count = $count +1) { echo $count; echo “ “; }

The format used in this example is typical of many used in PHP, sets up a counter, checks the counter and increments the counter. It is possible to have more than one condition, and these are separated by commas. This leads to quite complex syntax, an example of which is given below (if you find yourself writing code this complex, go and lay down in a dark room until the urge to code any more passes !):

for($num1=0,$num2=0; $num1<100&&$num2<$num3; $num1++,$num2+=2);

A Practical Example One of the ‘classic’ examples for using loops is to produce a times table. We are going to develop the code for a web page which shows the timetables up to ‘12 times’. As we will see this requires a loop inside another loop. This is called a nested loop – and is not as complex as it sounds. First lets examine the logic of what is required, and then the actual PHP code. We will use HTML for the basic page, headings etc and PHP for the loops algorithms. The intention is to produce a page that looks like this:

Notice that a loop is required to count from 1 to 12, this is to first produce the one times table, then the two times table, the three times table etc. With each iteration of the loop we need to pause and have a second loop from 1 to 12. To clarify, the first loop determines which times table we are generating. When this first loop reaches the first value we pause (at the value 1), and then have a second loop generate 1 times 1, 1 times 2, 1 times 3 ….1 times 12. At this point the second loop stops, as it has done its job. The first loop continues and move on to the value 2. We pause whilst the second loop starts again and generates 2 times 1, 2 times 2, 2 times 3, up to 2 times 12. Again the second loop ceases execution, and we continue

until eventually the first loop has reached the value 12.

Page 24: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 24 of 25

The following is the code for this timetable. Read it carefully and ensure you understand how the loops work, in particular how they are nested to work in tandem. Type it up, ensure it works, and try amending the loop values to see the effect. <html> <head> <title>The Times-Tables</title> </head> <body bgcolor="#ffffff"> <h1>The Times Tables</h1> <?php // Go through each table for($table=1; $table<13; $table++) { echo "<p><b>The " . $table . " Times Table</b>\n"; // Produce 12 lines for each table for($counter=1; $counter<13; $counter++) { $answer = $table * $counter; // Is this an even-number counter? if ($counter % 2 == 0) // Yes, so print this line in bold echo "<br><b>$counter x $table = " . "$answer</b>"; else // No, so print this in normal face echo "<br>$counter x $table = $answer"; } } ?> </body> </html> The only command which is not familiar to you at this stage is in the line:

if ($counter % 2 == 0) This uses ‘%’ to carry out a ‘Div’ function. It divides by 2 and looks at the ‘remainder’. If the remainder is zero, having divided by two, it must be an even number (a useful technique, please note). The ‘if’ statement continues to print even numbers in bold, odd numbers in plain text. The two loops are ‘table’ to determine which table is being calculated, and ‘counter’ which determines which number is being used in the table.

Page 25: Php Work Book

PHP Workbook

Brendan Riordan & Matthew Green - Page 25 of 25

Exercise 1 - Produce a PHP script which counts from 1 to 100, and displays any numbers which have a factor of four (Hint: see how to use the ‘Div’ function above). Exercise 2 – Develop a page which on the first line writes a single ‘1’, on the second line it should produce two ‘2’s, on the third line it should write three ‘3’s, and so on up to 9. Exercise 3 – Write a nested loop, which displays a representation of a chess board. It should have eight rows of eight columns, with each black square represented by a ‘[X]’, and each white square represented by ‘[ ]. Again, the ‘Div’ function will help you decide which are black, and which are white squares. Remember, they alternate position after each row. Exercise 4 – Define a constant ‘my_year’ to the year of your birth. A loop should randomly generate numbers in the range 1900 to 1999, each number should be displayed on screen. This should continue until the number which has been randomly generated matches the year of your birth. The code to generate a random number in this range is given below:

$any_year = rand(1900, 1999); print $any_year; Exercise 5 – Finally, for a bit of fun, write a PHP script which contains the single line phpinfo(); Examine the environment variables, and research how you might use these to report back to a viewr of your web site, their IP address, which version of Windows they are using, which Internet browser they are using etc