"\n"; print " \n"; print " My web page\n"; ... for ($i = 1; $i <= 10; $i++) { print "

I can count to $i!

\n"; } ?> HTML best PHP style is to minimize print/echo statements in embedded PHP code but without print, how do we insert dynamic content into the page?"> "\n"; print " \n"; print " My web page\n"; ... for ($i = 1; $i <= 10; $i++) { print "

I can count to $i!

\n"; } ?> HTML best PHP style is to minimize print/echo statements in embedded PHP code but without print, how do we insert dynamic content into the page?">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

More on PHP: Arrays, Functions and Files

Similar presentations


Presentation on theme: "More on PHP: Arrays, Functions and Files"— Presentation transcript:

1 More on PHP: Arrays, Functions and Files
CMPT241 Web Programming More on PHP: Arrays, Functions and Files

2 Printing HTML tags in PHP = bad style
print "<!DOCTYPE html>"\n"; print " <head>\n"; print " <title>My web page</title>\n"; ... for ($i = 1; $i <= 10; $i++) { print "<p> I can count to $i! </p>\n"; } ?> HTML best PHP style is to minimize print/echo statements in embedded PHP code but without print, how do we insert dynamic content into the page?

3 PHP expression blocks The answer is 42 output
<?= expression ?> PHP <h2> The answer is <?= 6 * 7 ?> </h2> PHP The answer is output PHP expression block: a small piece of PHP that evaluates and embeds an expression's value into HTML <?= expression ?> is equivalent to: useful for embedding a small amount of PHP (a variable's or expression's value) in a large block of HTML without having to switch to "PHP-mode" <?php print expression; ?> PHP

4 Expression block example
<!DOCTYPE html> <head><title>Embedded PHP</title> </head> <body> <?php for ($i = 99; $i >= 1; $i--) { ?> <p> <?= $i ?> bottles of beer on the wall, <br /> <?= $i ?> bottles of beer. <br /> Take one down, pass it around, <br /> <?= $i - 1 ?> bottles of beer on the wall. </p> } </body> </html> PHP

5 Common errors: unclosed braces, missing = sign
... <body> <p>Watch how high I can count: <?php for ($i = 1; $i <= 10; $i++) { ?> <? $i ?> </p> </body> </html> PHP if you forget to close your braces, you'll see an error about 'unexpected $end' if you forget = in <?=, the expression does not produce any output

6 Complex expression blocks
... <body> <?php for ($i = 1; $i <= 3; $i++) { ?> <h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>> } </body> PHP This is a level 1 heading. This is a level 2 heading. This is a level 3 heading output

7 Arrays Append: use bracket notation without specifying an index
$name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # append PHP $a = array(); # empty array (length 0) $a[0] = 23; # stores 23 at index 0 (length 1) $a2 = array("some", "strings", "in", "an", "array"); $a2[] = "Ooh!"; # add string to end (at index 5) PHP Append: use bracket notation without specifying an index Element type is not specified; can mix types

8 Arrays $a2 = array("some", "strings", "in", "an", "array");
$a2[100] = "Ooh!"; # add string to end (at index 100) PHP

9 Array functions function name(s) description count(a)
number of elements in the array print_r (a) print array's contents array_pop(a), array_push(a,value), array_shift(a), array_unshift(a,value) using array as a stack/queue in_array(value,a), array_search(value,a), array_reverse(a), sort(a), rsort(a), shuffle(a) searching and reordering array_merge(a1,a2,...), array_intersect(a1,a2,...), array_diff(a1,a2), array_slice(a,start,len) creating, filling, filtering array_sum(a), array_product(a), array_unique(a) processing elements

10 Array function example
$tas = array("MD", "BH", "KK", "HM", "JP"); for ($i = 0; $i < count($tas); $i++) { $tas[$i] = strtolower($tas[$i]); } $morgan = array_shift($tas); array_pop($tas); array_push($tas, "ms"); array_reverse($tas); sort($tas); $best = array_slice($tas, 1, 2); # subarray PHP Maybe delete the comments that give out the output # ("md", "bh", "kk", "hm", "jp") # ("bh", "kk", "hm") # ("bh", "kk", "hm", "ms") # ("ms", "hm", "kk", "bh") # ("bh", "hm", "kk", "ms") # ("hm", "kk") the array in PHP replaces many other collections in Java list, stack, queue, set, map, ...

11 foreach loop You cannot use a foreach loop to modify the elements
foreach ($array as $variableName) { ... } PHP for ($i = 0; $i < count($fellowship); $i++) { print "$fellowship[$i]\n"; } foreach ($fellowship as $fellow) { print "$fellow\n"; } PHP One bad thing with foreach: you cannot change the value of the variable after “as”, you can just assign it a value, it does not have the value in the table You cannot use a foreach loop to modify the elements

12 Splitting/joining strings
$array = explode(delimiter, string); $string = implode(delimiter, array); PHP explode and implode convert between strings and arrays $s = “MC CMPT 241"; $a = explode(" ", $s); # ("MC", “CMPT", “241") $s2 = implode("...", $a); # “MC...CMPT...241" PHP

13 Example with explode Marty D Stepp Jessica K Miller Victoria R Kirst contents of input file names.txt explode and implode convert between strings and arrays foreach (file("names.txt") as $name) { $tokens = explode(" ", $name); ?> <p> author: <?= $tokens[2] ?>, <?= $tokens[0] ?> </p> <?php } PHP author: Stepp, Marty author: Miller, Jessica author: Kirst, Victoria output

14 Unpacking an array: list
list($var1, ..., $varN) = array; PHP $values = array(“mundruid", "18", “f”); ... list($username, $age, $gender) = $values; PHP the list function accepts a comma-separated list of variable names as parameters use this to quickly "unpack" an array's contents into several variables a convenience, so you can refer to $username instead of $values[0], etc.

15 Example explode Harry Potter, J.K. Rowling
The Lord of the Rings, J.R.R. Tolkien Dune, Frank Herbert contents of input file books.txt <?php foreach (file(“books.txt") as $book) { list($title, $author) = explode(“,", $book); ?> <p> Book title: <?= $title ?>, Author: <?= $author ?> </p> <?php } ?> PHP

16 PHP Arrays Exercise For this exercise, you will use a list of ten of the largest cities in the world. (Please note, these are not the ten largest, just a selection of ten from the largest cities.) Create an array with the following values: Tokyo, Mexico City, New York City, Mumbai, Seoul, Shanghai, Lagos, Buenos Aires, Cairo, London. Print these values to the browser separated by commas, using a loop to iterate over the array. Sort the array, then print the values to the browser in an unordered list, again using a loop. Add the following cities to the array: Los Angeles, Calcutta, Osaka, Beijing. Sort the array again, and print it once more to the browser in an unordered list.

17 Multidimensional Arrays
<?php $AmazonProducts = array( array(“BOOK", "Books", 50), array("DVDs", “Movies", 15), array(“CDs", “Music", 20)); for ($row = 0; $row < 3; $row++) { for ($column = 0; $column < 3; $column++) { ?> <p> | <?= $AmazonProducts[$row][$column] ?> <?php } ?> </p> <?php } ?> PHP Maybe delete the comments that give out the output

18 Functions parameter types and return types are not written
function name(parameterName, ..., parameterName) { statements; } PHP function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; } PHP parameter types and return types are not written a function with no return statements implicitly returns NULL can be declared in any PHP block, at start/end/middle of code

19 Calling functions name(expression, ..., expression); PHP $w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h); PHP if the wrong number of parameters are passed, it's an error

20 Default Parameter Values
function print_separated($str, $separator = ", ") { if (strlen($str) > 0) { print $str[0]; for ($i = 1; $i < strlen($str); $i++) { print $separator . $str[$i]; } } PHP print_separated("hello"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-o PHP Any parameters with default values must appear at the end of the list if no value is passed, the default will be used

21 Value vs. Reference Parameters
function make_bigger($num){ $num = $num * 2; } $x = 5; make_bigger($x); print $x; PHP function make_bigger(&$num){ $num = $num * 2; } $x = 5; make_bigger($x); print $x; PHP

22 Variable scope: global and local vars
$dept = “CMPT"; # global ... function course_number() { global $dept; $suffix = “241"; # local $course = $dept. $suffix; print "$course“; } PHP variables declared in a function are local to that function; others are global if a function wants to use a global variable, it must have a global statement but don't abuse this; mostly you should use parameters

23 Note PHP has no narrower scope than function-level.
Variables are destroyed when the function returns Variable scope is completely unrelated to the start and end of PHP <?php ... ?> blocks. function scope_example(){ for ($i = 0; $i < 10; $i++){ print “Hello”; $x = 42; } print $i; print $x; } PHP

24 PHP file I/O functions function name(s) category
file, file_get_contents, file_put_contents reading/writing entire files basename, file_exists, filesize, fileperms, filemtime, is_dir, is_readable, is_writable, disk_free_space asking for information copy, rename, unlink, chmod, chgrp, chown, mkdir, rmdir manipulating files and directories glob, scandir reading directories

25 Reading from/Writing to a file
# reverse a file $text = file_get_contents("poem.txt"); $text = strrev($text); file_put_contents("poem.txt", $text); PHP file_get_contents returns entire contents of a file as a string file_put_contents writes a string into a file, replacing any prior contents

26 file_get_contents If the file doesn’t exist, an empty string is returned and a warning is issued. Suppress the warning message @file_get_contents

27 Appending to a file old contents new contents Roses are red,
# add a line to a file $new_text = "P.S. ILY, GTG TTYL!~"; file_put_contents("poem.txt", $new_text, FILE_APPEND); PHP old contents new contents Roses are red, Violets are blue. P.S. ILY, GTG TTYL!~ file_put_contents can be called with an optional third parameter appends (adds to the end) rather than replacing previous contents

28 Reading files contents of foo.txt file("foo.txt")
file_get_contents("foo.txt") Hello how are you? I'm fine array( "Hello\n", #0 "how are\n", #1 "you?\n", #2 "\n", #3 "I'm fine\n" #4 ) "Hello\n how are\n you?\n \n I'm fine\n" file returns lines of a file as an array file_get_contents returns entire contents of a file as a string

29 The file function # display lines of file as a bulleted list $lines = file("todolist.txt"); foreach ($lines as $line) { ?> <li> <?= $line ?> </li> <?php } ?> PHP file returns the lines of a file as an array of strings each string ends with \n to strip the \n off each line, use optional second parameter: $lines = file("todolist.txt",FILE_IGNORE_NEW_LINES); PHP

30 Reading directories function description scandir
returns an array of all file names in a given directory (returns just the file names, such as "myfile.txt") glob returns an array of all file names that match a given pattern (returns a file path and name, such as "foo/bar/myfile.txt") glob can filter by accepting wildcard paths with the * character

31 Example for scandir . .. 2009_w2.pdf 2007_1099.doc output <ul>
<?php $folder = "taxes/old"; foreach (scandir($folder) as $filename) { ?> <li> <?= $filename ?> </li> } </ul> PHP annoyingly, the current directory (".") and parent directory ("..") are included in the array don't need basename with scandir because it returns the file's names only . .. 2009_w2.pdf 2007_1099.doc output

32 Example for glob glob can match a "wildcard" path with the * character
# reverse all poems in the poetry directory $poems = glob("poetry/poem*.dat"); foreach ($poems as $poemfile) { $text = file_get_contents($poemfile); file_put_contents($poemfile, strrev($text)); print "I just reversed " . } PHP glob can match a "wildcard" path with the * character

33 PHP Include File Insert the content of one PHP file into another PHP file before the server executes it Use the include() generates a warning if file not found, but the script will continue execution require() generates a fatal error, and the script will stop Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).

34 include() example <html> <body>
<a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/references.php">References</a> <a href="/examples.php">Examples</a> <a href="/contact.php">Contact Us</a> HTML/PHP <html> <body> <div class="leftmenu"> <?php include("menu.php"); ?> </div> <h1>Welcome to my home page.</h1> <p>I have a great menu here.</p> </body> </html> PHP

35 Query strings and parameters
URL?name=value&name=value PHP PHP query string: a set of parameters passed from a browser to a web server often passed by placing name/value pairs at the end of a URL above, parameter username has value stepp, and sid has value  PHP code on the server can examine and utilize the value of parameters a way for PHP code to produce different output based on values passed by the user

36 Query parameters: $_GET
$user_name = $_GET["username"]; $id_number = (int) $_GET["id"]; $eats_meat = FALSE; if (isset($_GET["meat"])) { $eats_meat = TRUE; } PHP $_GET["parameter name"] returns a parameter's value as a string test whether a given parameter was passed with isset

37 Object Oriented PHP

38 Case Study GRE word of the day

39 Homework 7 .php page supporting .css file
Must at least use arrays and files Something similar to the case study (GRE word of the day) we did in class

40 Project 3 Due Date: Friday April 3, 2015

41 Final Project Team members
Up to 3 people in a team Decide by Tuesday March 31 Start thinking about what project you want to work on Must use PHP, CSS and JavaScript Proposal is due on April 17.


Download ppt "More on PHP: Arrays, Functions and Files"

Similar presentations


Ads by Google