Table of Contents

~~SLIDESHOW~~

Introduction to PHP (Part 2)

Supplementary Material

Provided for Reference. This material is no longer taught on this module.

Lecturer: Dr Chris P. Jobling.

More on the language features of PHP

Introduction to PHP (Part 2)

We continue our review of the Basics of PHP with a discussion of arrays, functions and regular expressions.


Based on Chapter 12 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. and Chapter 12 of Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.

Contents of this Lecture

Further features of the PHP language with examples

The Examples for PHP Part 2.

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  1. In what two ways can arrays in PHP be created?
  2. What keys are used when an array is created but no keys are specified?
  3. Must all of the values of an array be of the same type?
  4. Must all of the keys of an array be of the same type?
  5. What exactly do the array_keys and array_values functions do?

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What exactly does the in_array function do?
  2. Explain the actions of the implode and explode functions.
  3. Describe the actions of the next, reset, and prev functions.
  4. What are the syntax and semantics of the two forms of the foreach statement?
  5. Describe the result of using the sort function on an array that has both string and numeric values.

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What is the difference between the sort and asort functions?
  2. What happens if a script defines the same function more than once?
  3. Are function names case sensitive?
  4. What value is returned by a function if its execution does not end by executing a return statement?

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What are the two ways you can specify that a parameter is to be passed by reference?
  2. How can a variable used outside a function be accessed by the function?
  3. How can you define a variable in a function so that its lifetime extends beyond the time the function is in its first execution?

Arrays

Array creation

    $list = array(0 => "apples", 1 => "oranges", 2 => "grapes")

Array creation (continued)

Array elements

    $list = array("make" => "Cessna", "model" => "C210", 
                  "year" => 1960, 3 => "sold");
 
    $list = array(1, 3, 5, 7, 9);
 
    $list = array(5, 3 => 7, 5 => 10, "month" => "May");
 
    $colours = array('red', 'blue', 'green', 'yellow');

Accessing array elements

    $list[4] = 7;
    $list["day"] = "Tuesday";
    $list[] = 17;

Accessing array elements

    $highs = array("Mon" => 74, "Tue" => 70,
                   "Wed" => 67, "Thu" => 62,
                   "Fri" => 65);
    $days = array_keys($highs);
    $temps = array_values($highs);

Dealing with Arrays

    unset($list);
    unset($list[4]);  # No index 4 element now

Dealing with Arrays (continued)

Internal structure of arrays

The logical internal structure of arrays in PHP

Sequential access to array elements

    $colours = array("blue", "red", "green", "yellow");
    $colour = current($colours);
    print("$colour <br />");
    while ( $colour = next($colours) ) {
      print ("$colour <br />");
    }

Sequential access to array elements (continued)

    while ( $element = each($colours) ) {
      print ("$element['value'] <br />");
    }

Sequential access to array elements (continued)

Sequential access to array elements (continued)

    foreach ($colours as $colour) {
      print "Is $colour your favourite colour?<br />";
    }

Is red your favourite colour?

Is blue your favourite colour?
Is green your favourite colour?
Is yellow your favourite colour?

Sequential access to array elements (continued)

    foreach ($colours as $key => $colour) { ... }
    $ages = array("Bob" => 42, "Mary" => 43);
    foreach ($ages as $name => $age) {
      print("$name is $age years old <br />");
    }

Sorting Arrays

    $list = ('h', 100, 'c', 20, 'a');
    sort($list);
    // Produces ('a', 'c', 'h'‘, 20, 100)

Sorting Arrays (continued)

    sort($list, SORT_NUMERIC);

More sorting functions

    $list("Fred" => 17, "Mary" => 21, "Bob" => 49, "Jill" => 28);
    ksort($list);
    // $list is now ("Bob" => 49, "Fred" => 17, "Jill" => 28, "Mary" => 21)

Example of Array Sorting


<<!DOCTYPE html>
 
<!-- sorting.php - An example to illustrate several of the
     sorting functions -->
<html lang="en">
  <head> 
    <meta charset="utf-8" />
    <title> sorting.php - An example to illustrate several of the
     sorting functions </title>
  </head>
  <body>
    <?php
       $original = array("Fred" => 31, "Al" => 27,
                         "Gandalf" => "wizzard",
                         "Betty" => 42, "Frodo" => "hobbit");
    ?>
    <h4> Original Array </h4>
    <?php
      foreach ($original as $key => $value) {
         print("[$key] => $value <br />");
      }
    ?>
    <h4> Array sorted with sort </h4>
    <?php
      $new = $original;
      sort($new);
       foreach ($new as $key => $value) {
         print("[$key] = $value <br />");
       }
    ?>
    <h4> Array sorted with asort </h4>
    <?php
       $new = $original;
       asort($new);
       foreach ($new as $key => $value) {
         print("[$key] = $value <br />");
       }
    ?>
    <h4> Array sorted with ksort </h4>
    <?php
       $new = $original;
       ksort($new);
       foreach ($new as $key => $value) {
         print("[$key] = $value <br />");
       }
    ?>
  </body>
</html> 

Result of running the sort.php example

User-Defined Functions

    function function_name( [formal_parameters] ) {
      ...
    }

General Characteristics of Functions

Function Parameters

Function Parameters (continued)

    function addOne(&$param) {
       $param++;
    }
 
    $it = 16;
    addOne($it);  // $it is now 17

Function Parameters (continued)

    function subOne($param) {
      $param--;
    }
 
    $it = 16;
    subOne(&$it);   // $it is now 15

Return Values

   function &newArray($x) { ... }

The Scope of Variables

   global $sum;

The Lifetime of Variables

    static $sum = 0;  # $sum is static

Pattern Matching

        preg_match(regex, str [,array])

Example

The word_table.php (word_table.php @ localhost) example illustrates the use of functions and regular expressions


<!DOCTYPE html>
<!--    word_table.php
 
Uses a function to split a given string of text into
its constituent words. It also determines the frequency of
occurrence of each word. The words are separated by
whitespace or punctuation, possibly followed by whitespace.
The punctuation can be a period, a comma, a semicolon, a
colon, an exclamation point, or a question mark.
The main driver program calls the function and displays
the results.
-->
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title> Word Table </title>
  </head>
  <body>
    <?php
 
    // Function splitter
    //  Parameter: a string of text containing words and punctuation
    //  Returns: an array in which the unique words of the string are
    //           the keys and their frequencies are the values.
 
    function splitter($str) {
 
      // Create the empty word frequency array
 
      $freq = array();
 
      // Split the parameter string into words
 
      $words = preg_split("/[ .,;:!?]\s*/", $str);
 
      // Loop to count the words (either increment or initialize to 1)
 
      foreach ($words as $word) {
        $keys = array_keys($freq);
        if (in_array($word, $keys))
          $freq[$word]++;
        else
          $freq[$word] = 1;
      }
 
      return $freq;
    }#** End of splitter

    // Main test driver
 
    $str = "apples are good for you, or don't you like apples?
or maybe you like oranges better than apples";
 
    // Call splitter
 
    $tbl = splitter($str);
 
    // Display the words and their frequencies
 
    print "<br /> Word Frequency <br /><br />";
    $sorted_keys = array_keys($tbl);
    sort($sorted_keys);
    foreach ($sorted_keys as $word) {
      print "$word $tbl[$word] <br />";
    }
  ?>
  </body>
</html>
Word Frequency

apples 3
are 1
better 1
don't 1
for 1
good 1
like 2
maybe 1
or 2
oranges 1
than 1
you 3

Summary of this Lecture

Further features of the PHP language with examples

The Examples for PHP Part 2.

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  1. In what two ways can arrays in PHP be created?
  2. What keys are used when an array is created but no keys are specified?
  3. Must all of the values of an array be of the same type?
  4. Must all of the keys of an array be of the same type?
  5. What exactly do the array_keys and array_values functions do?

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What exactly does the in_array function do?
  2. Explain the actions of the implode and explode functions.
  3. Describe the actions of the next, reset, and prev functions.
  4. What are the syntax and semantics of the two forms of the foreach statement?
  5. Describe the result of using the sort function on an array that has both string and numeric values.

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What is the difference between the sort and asort functions?
  2. What happens if a script defines the same function more than once?
  3. Are function names case sensitive?
  4. What value is returned by a function if its execution does not end by executing a return statement?

Learning Outcomes (continued)

At the end of this lecture you should be able to answer these questions:

  1. What are the two ways you can specify that a parameter is to be passed by reference?
  2. How can a variable used outside a function be accessed by the function?
  3. How can you define a variable in a function so that its lifetime extends beyond the time the function is in its first execution?

Homework Exercises

Write the following PHP functions and code to test them

  1. Parameter: An array of strings. Return value: A list of the unique strings in the parameter array.
  2. Parameter: an array of numbers. Return value: The average and median of the parameter array.
  3. Parameter: A string of numbers separated by spaces. Return value: The first four-digit number in the string.

Homework Exercises (continued)

  1. Modify the sample script word_table.php discussed in this lecture to place the output table in an XHTML table.

These and other PHP exercises are also available on the homework page.

What's Next?

PHP for Web Applications

Previous Lecture | home | Next Lecture

1)
PPHP 5 supports classes, so it may be possible to use overloading for polymorphism