modified from moseley ’s sli desweb applications development. lecture 5 slide 1 lecture 5:...

44
Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 1 Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Upload: garey-atkins

Post on 05-Jan-2016

219 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 1Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 1

Lecture 5: Introduction to PHP

Instructor: Dr. Mohammad Anwar Hossain

Page 2: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 2Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 2

Introduction to PHP

•PHP – history and getting start•PHP - Overview•Variables & Scope•Output •Variable types ; Boolean; Strings •String Functions & Parsers•Screening User Input/Output •Maths functions •Control and flow

Today:

Page 3: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 3Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 3

PHP• PHP is a scripting language that allows you to create dynamic

Web pages

• PHP-Hypertext Preprocessor.

Other Names : Personal Home Page, Professional Home Page

• You can embed PHP scripting within normal html coding

• PHP was designed primarily for the Web

• PHP includes a comprehensive set of database access functions

• High performance/ease of learning/low cost

Page 4: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 4Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 4

PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix.

PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.

PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans .

PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added.

PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP

Brief History of PHP

Page 5: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 5Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 5

As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP Addresses http://www.php.net/usage.php This is roughly 32% of all

domains on the web.

Brief History of PHP

Page 6: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 6

Why is PHP used?

1. Easy to UseCode is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode".

<html>   <head>       <title>Example</title>   </head>   <body>     <?php        echo "Hi, I'm a PHP script!";        ?>

   </body></html>

Page 7: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 7

Why is PHP used?

2. Cross PlatformRuns on almost any Web server on several operating systems.One of the strongest features is the wide range of supported databases

Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server

Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003

Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm

Page 8: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 8

Why is PHP used?

PHP

Software Free

Platform Free (Linux)

Development Tools Free

PHP Coder, jEdit

3. Cost BenefitsPHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free.

Page 9: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 9

Getting Started

1. How to escape from HTML and enter PHP mode• PHP parses a file by looking for one of the special tags that

tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag.

Starting tag Ending tag Notes

<?php ?> Preferred method as it allows the use of PHP with XHTML

<? ?> Not recommended. Easier to type, but has to be enabled and may conflict with XML

<script language="php"> ?> Always available, best if used when FrontPage is the HTML editor

<% %> Not recommended. ASP tags support was added in 3.0.4

<?php echo “Hello World”; ?>PHP CODE HTMLHTML

Page 10: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 10

Getting Started

2. Simple HTML Page with PHP• The following is a basic example to output text using

PHP.

<html><head><title>My First PHP Page</title></head><body><?phpecho "Hello World!";?></body></html>

Copy the code onto your web server and save it as “test.php”.

You should see “Hello World!” displayed.

Notice that the semicolon is used at the end of each line of PHP code to signify a line break. Like HTML, PHP ignores whitespacebetween lines of code. (An HTML equivalent is <BR>)

Page 11: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 11

Getting Started

3. Using conditional statements• Conditional statements are very useful for displaying

specific content to the user. The following example shows how to display content according to the day of the week.

<?php$today_dayofweek = date(“w”);

if ($today_dayofweek == 4){ echo “Today is Thursday!”; }else{ echo “Today is not Thursday.”;}

?>

Page 12: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 12

Getting Started

3. Using conditional statementsThe if statement checks the value of $today_dayofweek (which is the numerical day of the week, 0=Sunday… 6=Saturday)

If it is equal to 4 (the numeric representation of Thurs.) it will display everything within the first { } bracket after the “if()”.

If it is not equal to 4, it will display everything in the second { } bracket after the “else”.

<?php$today_dayofweek = date(“w”);

if ($today_dayofweek == 4){ echo “Today is Thursday!”; }else{ echo “Today is not Thursday.”;}

?>

Page 13: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 13

Getting Started3. Using conditional statements

If we run the script on a Thursday, we should see: “Today is Thursday”.

On days other than Thursday, we will see: “Today is not Thursday.”

<?php$today_dayofweek = date(“w”);

if ($today_dayofweek == 4){ echo “Today is Thursday!”; }else{ echo “Today is not Thursday.”;}

?>

Page 14: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 14Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 14

Basics of PHP

• PHP files end with .php

you may see .php3 .phtml .php4 as well • PHP code is contained within tags • <?php ?> or Short-open: <? ?> • HTML script tags: <script language="php"> </script>

Page 15: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 15Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 15

Output

• Most things in PHP execute silently • You need to explicitly ask PHP to generate output • Echo is not a function and cannot return a value

– echo "<p>This is a paragraph.</p>";

• Print is a function and returns a value – 1 = success, 0 = failure– print ("<p>This is a paragraph too.</p>");

• Use echo or print statements and View Source for debugging your code

Page 16: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 16Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 16

Variables

• All variables begin with $ and can contain letters, digits and underscore (and no digit directly after the $)

• The value of a variable is the value of its most recent assignment

• Don’t need to declare variables • Variables have no intrinsic type other than the type of

their current value • Can have variable variables $$variable

– Like a pointer variable type; best to avoid

Page 17: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 17Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 17

Variables Scope• Scope refers to where within a script or program a

variable has meaning or a value • Mostly script variables are available to you anywhere

within your script. • Note that variables inside functions are local to that

function and a function cannot access script variables outside the function even if they are in the same file.

• The modifiers global and static allow function variables to be accessed outside the function or to hold their value between function calls respectively

Page 18: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 18Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 18

Variable types

• Strings • Numbers

– Integers– doubles

• Booleans– TRUE / FALSE

• Arrays • Objects

Page 19: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 19Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 19

Variable Examples• Integer$a = 1234; # decimal number$a = -123; # a negative number$a = 0123; # octal number (equivalent to 83 decimal)$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)• Floating Point Numbers$a = 1.234; $a = 1.2e3; $a = 7E-10;• Boolean$foo = True; // assign the value TRUE to $foo

// == is an operator which returns a boolean if ($action == "show_version") { echo "The version is 1.23"; } // this is not necessary: if ($show_separators == TRUE) { echo "<hr>\n"; } // because you can simply type this: if ($show_separators) { echo "<hr>\n"; }

Page 20: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 20Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 20

Variable Examples cont.• Strings (single or double quoted) echo 'this is a simple string'; echo 'You can also have embedded newlines in strings, like this way.'; echo 'Arnold once said: "I\'ll be back"'; // output: ... "I'll be back"echo 'Are you sure you want to delete C:\*.*?'; // output: ... delete C:\*.*?• Arrays$error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning";$error_descriptions[E_NOTICE] = "This is just an informal notice";

the last example is in fact the same as writing: $error_descriptions[1] = "A fatal error has occured";$error_descriptions[2] = "PHP issued a warning";$error_descriptions[8] = "This is just an informal notice";(The first method is useful if E_ERROR is defined as a constant etc).

Page 21: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 21Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 21

Constants and Globals

To define a constant:define(“PI”, 3.1416);$area = PI*$radius*$$radius ;

Globals:◦ Defined outside any function; eg form variables…global $var1, $var2 ……function xyz() { $localvarX = $var1 …}

Page 22: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 22Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 22

Arrays in PHP

• An array in PHP is actually an ordered map which maps values to keys. An array can be thought of in many ways. Each of the concepts below can be implemented in a PHP array, so you can choose which ever of these ideas that you understand to conceptualise an array.

• linearly indexed array • list (vector) • hashtable (which is an implementation of a map) • dictionary • collection • stack (LIFO) • queue (FIFO) • can easily simulate trees and linked lists with arrays

of arrays

Page 23: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 23Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 23

Numerically-indexed arrays (Vector array)

Say that we have a list of marks out of 100 in a subject 95, 93, 56, 70, 65, 98◦ array value 1 - 95 ◦ array value 2 - 93 ◦ array value 3 - 56 ◦ array value 4 - 70 ◦ array value 5 - 65 ◦ array value 6 - 98

$marks = array (95, 93, 56, 70, 65, 98); generates a numerically-indexed array$marks[0] = 95 ;$marks[1] = 93 ;$marks[2] = 56 ;$marks[3] = 70 ;$marks[4] = 65 ;$marks[5] = 98 ;

Page 24: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 24Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 24

Numerically-indexed arrays (cont)

The following code also generates a numerically-indexed array, allocating the next index after the highest current index to the element.◦ $marks[] = 95;◦ $marks[] = 93;

marks[0] is 95 and marks[1] is 93. Note that array indexes start at 0 by default.You can skip indices by allocating a specific index

to a value -◦ $marks[5] = 56;◦ $marks[] = 70;

will be allocate 70 to $marks[6].marks[5] is 56 and marks[6] is 70.

Page 25: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 25Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 25

Associative arrays

• Say we have a list of marks out of 100 in a subject and we want to know who got what mark:• Adrian - 95, Matty - 93, Lance - 56, Stephen - 70,

Craig - 65, Andy - 98$marks = array ("Adrian"=>93, "Lance"=>56,

"Stephen"=>70, "Craig"=>65, "Andy"=>98);

• maps a value to a key • name is the key • mark is the value

Page 26: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 26Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 26

List an associative array

list() in conjunction with each() assigns a key / value pair into the variables $key and $variable. The following code prints each key / value pair into a table. Note that $value might itself be an array.

reset($marks); // go to the beginning of the array echo "<table border=\"1\">"while (list($key, $value) = each($marks)) { echo

"<tr><td>$key</td><td>$value</td></tr>\n"; } echo "</table><hr>";

Page 27: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 27Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 27

List an associative array (cont)

each() actually returns a array for each array item which includes the key and value as well as the index 0 mapped to the key and the index 1 mapped to the value. Reset() puts the index pointer back to 0. Hence if you are more comfortable with numeric indexes, you can do the following:

reset($marks); while ($row = each($marks)) { echo "Mark for $row[0] is $row[1]<br />"; }

Page 28: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 28Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 28

Strings

Dot operator for concatenation (joining) singly quoted read in and store literally double quoted certain sequences beginning with \ are replaced

with special characters + \n \t \r \$ \" \\ Variable names are replaced with string

representations of their values Variable interpolation No limit on string length

Page 29: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 29Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 29

String Functions

• boolean strcmp ($str1, $str2) • boolean strcasecmp ($str1, $str2) • boolean strstr ($str1, $str2) • boolean stristr ($str1, $str2) • int strlen($str) • string substr ($str, $start_pos, $len)

Page 30: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 30Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 30

String functions (cont)

• string chop ($str) • string ltrim ($str) • string trim ($str) • string str_replace ($old_txt, $new_txt, $text) • string substr_replace ($old_txt, $new_txt, $text) • strtolower($str) • strtoupper($str) • ucfirst($str) • ucwords($str)

Page 31: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 31Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 31

Formatting User Input/Output

• addslashes($str) • stripslashes($str) • escapeshellcmd($str) • strip_tags($str) • htmlspecialchars($str) • htmlentities($str) • nl2br($str) • …

Page 32: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 32Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 32

Maths functions

• + - / * % • ++ -- • += -= *= • = is set to (assignment)• = = is equivalent to eg $a == $b Equal TRUE if $a is equal

to $b.• = = = is identical to eg $a === $b Identical TRUE if $a is

equal to $b, and they are of the same type. (PHP 4 only) • $low_int = floor ($double) • $high_int = ceil ($double) • $nearest_int = round ($double)

• (nearest even number if exactly .5) • $positive = abs ($number) • $min = min ($n1, $n2 … , $nn) • $max = max ($n1, $n2 … , $nn)

Page 33: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 33Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 33

Control and flow

if (expr1) { } elseif (expr2) { } else { } while (cond) { } do { } while (cond) switch ($var) case a { } case b { } for ($i = 0; $i < expr; $i ++) { } foreach (array_expr as $value) { } foreach (array_expr as $key=>$value) { } breakcontinue

Page 34: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 34Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 34

If.. Then.. else

* if ($a > $b) print "a is bigger than b";* if ($a > $b) { print "a is bigger than b"; $b = $a; }* if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "a is smaller than b"; }

Page 35: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 35Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 35

While

/* example 1 */

$i = 1; while ($i <= 10) { print $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 - alternative notation to using the braces - : and endwhile*/ $i = 1; while ($i <= 10): print $i; $i++; endwhile;

Page 36: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 36Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 36

For loops

/* example 1 similar to C syntax */ for ($i = 1; $i <= 10; $i++) { print $i; } /* example 2 */ for ($i = 1;;$i++) { if ($i > 10) { break;

} print $i;

} /* example 3 */ $i = 1; for (;;) { if ($i > 10) { break; } print $i; $i++; } /* example 4 */ for ($i = 1; $i <= 10; print $i, $i++);

Page 37: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 37Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 37

Foreach

An easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first:

foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statementThe following are functionally identical: //example 1 // reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value<br>\n"; }//example 2 // foreach ($arr as $value) { echo "Value: $value<br>\n"; }

Page 38: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 38Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 38

Foreach cont.

/* foreach example 1: value only */$a = array (1, 2, 3, 17); foreach ($a as $v) { print "Current value of \$a: $v.\n"; } /* foreach example 2: value (with key printed for illustration) */ $a = array (1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach($a as $v) { print "\$a[$i] => $v.\n"; $i++; } /* foreach example 3: key and value */ $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; }

Page 39: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 39Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 39

Break & Continue

-break ends execution of the current for, foreach while, do..while or switch structure.

$arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); while (list ($key, $val) = each ($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br>\n";} /* note list() is a multiple assignment function; the key and value returned by each() are

assigned to $key and $value. $key is not used in this example.

-continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.

Page 40: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 40Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 40

Switch

if ($i == 0) { print "i equals 0"; }if ($i == 1) { print "i equals 1";}if ($i == 2) { print "i equals 2"; }/* this is equivalent */ switch ($i) { case 0:

print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; }

Page 41: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 41Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 41

require() and include()

• require() includes and evaluates a specific file.• require() and include() are identical in every way except how

they handle failure. include() produces a Warning while require() results in a Fatal Error.

<?php require 'prepend.php'; require $somefile;require ('somefile.txt');?>

• require_once() or include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Page 42: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 42Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 42

What we covered today:

• Introduction To PHP• Variables, constants, arrays and strings• Control structures – sequence, repetition and

selection

Page 43: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 43Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 43

Sources

• http://www.zend.com/zend/art/intro.php• http://www.php.net/• http://hotwired.lycos.com/webmonkey/

programming/php/index.html• www.phpbuilder.com

Page 44: Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain

Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 44Modified from Moseley’s slides Web Applications Development. Lecture 5 Slide 44

Next: More advanced PHP