SlideShare a Scribd company logo
IELM 511 Information Systems Design
                           Lab 4: Fundamental PHP functions: II

This lab will use a few more exercises to build up your experience with PHP scripts. In
subsequent labs, you will write CGI programs that connect to a Database and exchange
information with the DB, returning the feedback to the web client. Since most data in DBs
is stored in tables, and cell entries are mostly strings, therefore the two data types we need
to handle in our programs are (multi-dimensional) arrays, and strings. In this lab, we will
build up some more experience with these, working on basic language skills for PHP.

Objectives of this lab
Gain some familiarity with the following concepts:
(a) Basic data structures in PHP: multi-dimension arrays
(b) Program flow control: functions
(c) Regular expressions and string parsing.

As before, if you need to look up the syntax of some operator/function in PHP, you can use
a good online PHP tutorial site, such as: http://www.w3schools.com/PHP/

The lab tasks are below.

Step 1. [Re-use from past lab]. Make a simple web-form (file: run_cgi.html) with one
input field and one text-box field (use or modify the file given to you in the lab materials).

Step 2. Try the following code using phpDesigner, and then modify it as instructed.
In most php program, we work with strings; common examples:
    - If you read a line of data from a file, you will read it as a string of characters;
    - The most common data types stored in a Database are strings.
PHP provides several useful string functions and operators.

   <?php
    $x = "I love"; // declare a variable, $x, and define its value(of type string)
    $y = " PHP !"; // declare and define variable $y
    $z = $x . $y;     // the dot-operator, ‘.’ is used to join two or more strings.
    echo $z;     // This should print: I love PHP !
    echo "<br>";

     $z = $z . " Yes, " . $z . " Oh yes, " . $z;
     echo( $z); // This example shows how to join many strings using ‘.’
     echo "<br>";

     $z = str_replace( "love", "hate", $z); // replace a part of a string with another
     echo $z, "<br>";
if ( substr_count( $z, "hate") >= 2) {
    /* substr_count( ) counts no of times a sub-string
      occurs in a given string */
          echo "Oh no, why do you hate me so much ?", "<br>";
     }
   ?>

What you learnt:
1. Useful string functions: str_replace, substr_count.

Exercise: Modify the code above as follows: $x should store the abstract of a paper written
by your advisor (or your favorite professor). $y should be an array of keywords of the
paper. Your program should output how many times each keyword occurs in the abstract.


Step 3. User-defined functions and multi-dimensional arrays
In this example, you will learn:
     (i) How to define your own functions
     (ii) Note how to return values from your functions: these can be variables, arrays, etc.
     (iii) Learn how to define named constants (same as #define in C++)
     (iv) Learn some math functions in PHP
     (v) Learn how to use “printf” function for formatted output.

   <?php
    // We define a function to multiply a 1x2 vector with a 2x2 matrix
   function vect_mult_mat( $vec, $mat) {
     $out[0] = $vec[0] * $mat[0][0] + $vec[1] * $mat[1][0];
     $out[1] = $vec[0] * $mat[0][1] + $vec[1] * $mat[1][1];
     return $out;
   }

    // The define function is similar to #define in C++
    // PHP has all common math functions, e.g. sin, cos, …
   define ("PI", 3.1415926);
   $cos_theta = cos( PI/4.0);
   $sin_theta = sin( PI/4.0);
    // item-by-item definition of a multi-dimensional array
   $rot_matrix[0][0] = $cos_theta; $rot_matrix[0][1] = $sin_theta;
   $rot_matrix[1][0] = -1.0 * $sin_theta; $rot_matrix[1][1] = $cos_theta;
   $my_vector = array( 2.0, 2.0);
    // We call the function defined earlier; notice that it returns an array!
   $rotated_vector = vect_mult_mat( $my_vector, $rot_matrix);
   echo "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to
   [ $rotated_vector[0], $rotated_vector[1] ] <br>n";
// Notice how echo prints floating point numbers -- quite ugly!
    // For formatted output, it is better to use the printf function of PHP
   printf( "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ %4.2f,
   %4.2f ] <br>n", $rotated_vector[0], $rotated_vector[1] );
   ?>

What you learnt:
1. One way to define a multi-dimensional array. Such arrays will be very useful when you
need to handle data coming from a DB – since each DB table is similar to a 2D array.
2. One way to define and use your own functions in PHP; notice that our function worked
by passing the value of its arguments; PHP also allows you to pass references to arguments,
which is sometimes useful.
3. A simple use of the printf function; this function is quite useful in generating pretty
output.

Exercise: Modify the code above as follows. First create a multi-dimensional array called
$loans, with the data from the table below (no need to store the attribute names). Write a
function which takes a 2-dimensional array as input, and outputs an HTML table that looks
like the table below (namely, it prints the top row with the given attribute names, and then
the rows of the array). Your main PHP program should output sub-arrays from the input
array such that each sub-array has only the data for a particular loan (e.g. there will be an
array of three rows for L17). Call the print_table function once for each sub-array and
display the output via the web client.



  customer     loan_no amount      branch_name
 111-12-0000      L17      1000      Downtown
 222-12-0000      L23      2000       Redwood
 333-12-0000      L15      1500      Pennyridge
 444-00-0000      L93      500         Mianus
 666-12-0000      L17      1000      Downtown
 111-12-0000      L11      900       Round Hill
 999-12-0000      L17      1000      Downtown
 777-12-0000      L16      1300      Pennyridge




Step 4. Working with strings: Regular expressions.
When working with web-based applications and DB, you will often be processing data in the
form of strings of characters.
Regular expressions (RegExps) are a very powerful method to do pattern matching on
strings. Many string functions use RegExps.
<?php
       // Define a string
      $text = "Never let a fool kiss you, never let a kiss fool you";
      echo "Text is: $text <br>n";

       // Two ways to search for a constant string in a long string:
       // strstr( ), and preg_match( )
       // Notice how the ‘’ is used to escape the "-mark in the argument of echo.
      if ( strstr( $text, "fool") ) { echo "strstr: Found "fool" in text <br>n";}

      if ( preg_match( "/fool/", $text) ) { echo "preg_match: Found "fool" in text <br>n";}

       // preg_match_all( ) can be used for case-insensitive search,
       // and multiple matches
       // In the RegExp, the pattern to match is between the /…/
       // the ‘i’ at the end indicates that the match should be case-insensitive
      $no_of_hits = preg_match_all( "/never/i", $text, $matches);
      echo "preg_match_all: Found $no_of_hits instances of "never" in text; they were: ";
      for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
      echo "<br> n";

       // to catch all instances of ‘fool’ or ‘kiss’, use the ‘|’ in the RegExp
      $no_of_hits = preg_match_all( "/fool|kiss/", $text, $matches);
      echo "preg_match_all: Found $no_of_hits instances of "fool" or "kiss" in text; they
      were: ";
      for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
      echo "<br> n";
      ?>

What you learnt:
1. Regular expressions are in fact a very powerful concept; we only saw the simplest
RegExps. You will see many other uses in future labs – you can use RegExps to search for
very complicated and patterns.

Exercise: Write a CGI program that will receive the abstract of a paper submitted by a form
via a web client. Your CGI program should search for the following incorrectly spelt words
in the abstract. It should then return the same text to the web client, except that all the
incorrectly spelt words should be colored in red, and the corrected spelling is suggested in
brackets, in blue color.

List of incorrect spellings to check:
teh     the
Teh      The
acn      can
abotu about
actualyl actually

For example, if the input text is:
Teh quick brown fox acn jump over the lazy fox.
Then the output should be:
Teh [do you mean: The] quick brown fox acn [do you mean: can] jump over the lazy fox.


References:
1. HTML quick reference file.
2. PHP tutorials and function references: (from www.php.net)
3. PHP tutorial site: http://www.w3pop.com/learn/view/p/3/o/0/doc/php_ref_string/
4. Another PHP tutorial/reference: http://www.w3schools.com/PHP/php_ref_array.asp



Lab materials for IELM 511 prepared by WEI Xiangzhi, Dept of IELM, HKUST.

More Related Content

PPTX
PHP Powerpoint -- Teach PHP with this
PPTX
PHP Basics
PDF
Functions in PHP
PDF
Zend Certification Preparation Tutorial
ODP
PHP Web Programming
PDF
Practice exam php
ODP
Php Learning show
PDF
Zend Certification PHP 5 Sample Questions
PHP Powerpoint -- Teach PHP with this
PHP Basics
Functions in PHP
Zend Certification Preparation Tutorial
PHP Web Programming
Practice exam php
Php Learning show
Zend Certification PHP 5 Sample Questions

What's hot (20)

ODP
Introduction to Perl - Day 1
PDF
PHP7. Game Changer.
PDF
Improving Dev Assistant
PPTX
Data types in php
PPT
Class 5 - PHP Strings
PDF
Perl.Hacks.On.Vim
ODP
Introduction to Perl - Day 2
PDF
Perl programming language
ODP
Advanced Perl Techniques
ODP
perl usage at database applications
PPT
Manipulating strings
PPT
PPT
Download It
PDF
Ruby cheat sheet
PPT
Perl Presentation
PPTX
Subroutines in perl
PPT
Plunging Into Perl While Avoiding the Deep End (mostly)
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Introduction to Perl - Day 1
PHP7. Game Changer.
Improving Dev Assistant
Data types in php
Class 5 - PHP Strings
Perl.Hacks.On.Vim
Introduction to Perl - Day 2
Perl programming language
Advanced Perl Techniques
perl usage at database applications
Manipulating strings
Download It
Ruby cheat sheet
Perl Presentation
Subroutines in perl
Plunging Into Perl While Avoiding the Deep End (mostly)
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Ad

Similar to lab4_php (20)

PPT
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
PPT
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
PPT
Php i basic chapter 3
PDF
PHP Reviewer
DOC
php&mysql with Ethical Hacking
PDF
PHP Lec 2.pdfsssssssssssssssssssssssssss
PDF
Learn php with PSK
PPTX
Python Homework Help
PPT
PHP and MySQL with snapshots
PPT
Training on php by cyber security infotech (csi)
PDF
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
PPT
C Tutorials
PPT
Ruby on Rails
DOCX
Php interview questions
DOCX
Php interview questions
PDF
Object Oriented PHP - PART-2
PPT
Web Technology_10.ppt
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3
PHP Reviewer
php&mysql with Ethical Hacking
PHP Lec 2.pdfsssssssssssssssssssssssssss
Learn php with PSK
Python Homework Help
PHP and MySQL with snapshots
Training on php by cyber security infotech (csi)
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
C Tutorials
Ruby on Rails
Php interview questions
Php interview questions
Object Oriented PHP - PART-2
Web Technology_10.ppt
Ad

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
PDF
&lt;img src="../i/r_14.png" />
PDF
&lt;img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
&lt;img src="../i/r_14.png" />
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
KodekX | Application Modernization Development
PPTX
A Presentation on Artificial Intelligence
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Approach and Philosophy of On baking technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
cuic standard and advanced reporting.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KodekX | Application Modernization Development
A Presentation on Artificial Intelligence
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”
Approach and Philosophy of On baking technology
Unlocking AI with Model Context Protocol (MCP)
20250228 LYD VKU AI Blended-Learning.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine learning based COVID-19 study performance prediction
cuic standard and advanced reporting.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Understanding_Digital_Forensics_Presentation.pptx

lab4_php

  • 1. IELM 511 Information Systems Design Lab 4: Fundamental PHP functions: II This lab will use a few more exercises to build up your experience with PHP scripts. In subsequent labs, you will write CGI programs that connect to a Database and exchange information with the DB, returning the feedback to the web client. Since most data in DBs is stored in tables, and cell entries are mostly strings, therefore the two data types we need to handle in our programs are (multi-dimensional) arrays, and strings. In this lab, we will build up some more experience with these, working on basic language skills for PHP. Objectives of this lab Gain some familiarity with the following concepts: (a) Basic data structures in PHP: multi-dimension arrays (b) Program flow control: functions (c) Regular expressions and string parsing. As before, if you need to look up the syntax of some operator/function in PHP, you can use a good online PHP tutorial site, such as: http://www.w3schools.com/PHP/ The lab tasks are below. Step 1. [Re-use from past lab]. Make a simple web-form (file: run_cgi.html) with one input field and one text-box field (use or modify the file given to you in the lab materials). Step 2. Try the following code using phpDesigner, and then modify it as instructed. In most php program, we work with strings; common examples: - If you read a line of data from a file, you will read it as a string of characters; - The most common data types stored in a Database are strings. PHP provides several useful string functions and operators. <?php $x = "I love"; // declare a variable, $x, and define its value(of type string) $y = " PHP !"; // declare and define variable $y $z = $x . $y; // the dot-operator, ‘.’ is used to join two or more strings. echo $z; // This should print: I love PHP ! echo "<br>"; $z = $z . " Yes, " . $z . " Oh yes, " . $z; echo( $z); // This example shows how to join many strings using ‘.’ echo "<br>"; $z = str_replace( "love", "hate", $z); // replace a part of a string with another echo $z, "<br>";
  • 2. if ( substr_count( $z, "hate") >= 2) { /* substr_count( ) counts no of times a sub-string occurs in a given string */ echo "Oh no, why do you hate me so much ?", "<br>"; } ?> What you learnt: 1. Useful string functions: str_replace, substr_count. Exercise: Modify the code above as follows: $x should store the abstract of a paper written by your advisor (or your favorite professor). $y should be an array of keywords of the paper. Your program should output how many times each keyword occurs in the abstract. Step 3. User-defined functions and multi-dimensional arrays In this example, you will learn: (i) How to define your own functions (ii) Note how to return values from your functions: these can be variables, arrays, etc. (iii) Learn how to define named constants (same as #define in C++) (iv) Learn some math functions in PHP (v) Learn how to use “printf” function for formatted output. <?php // We define a function to multiply a 1x2 vector with a 2x2 matrix function vect_mult_mat( $vec, $mat) { $out[0] = $vec[0] * $mat[0][0] + $vec[1] * $mat[1][0]; $out[1] = $vec[0] * $mat[0][1] + $vec[1] * $mat[1][1]; return $out; } // The define function is similar to #define in C++ // PHP has all common math functions, e.g. sin, cos, … define ("PI", 3.1415926); $cos_theta = cos( PI/4.0); $sin_theta = sin( PI/4.0); // item-by-item definition of a multi-dimensional array $rot_matrix[0][0] = $cos_theta; $rot_matrix[0][1] = $sin_theta; $rot_matrix[1][0] = -1.0 * $sin_theta; $rot_matrix[1][1] = $cos_theta; $my_vector = array( 2.0, 2.0); // We call the function defined earlier; notice that it returns an array! $rotated_vector = vect_mult_mat( $my_vector, $rot_matrix); echo "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ $rotated_vector[0], $rotated_vector[1] ] <br>n";
  • 3. // Notice how echo prints floating point numbers -- quite ugly! // For formatted output, it is better to use the printf function of PHP printf( "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ %4.2f, %4.2f ] <br>n", $rotated_vector[0], $rotated_vector[1] ); ?> What you learnt: 1. One way to define a multi-dimensional array. Such arrays will be very useful when you need to handle data coming from a DB – since each DB table is similar to a 2D array. 2. One way to define and use your own functions in PHP; notice that our function worked by passing the value of its arguments; PHP also allows you to pass references to arguments, which is sometimes useful. 3. A simple use of the printf function; this function is quite useful in generating pretty output. Exercise: Modify the code above as follows. First create a multi-dimensional array called $loans, with the data from the table below (no need to store the attribute names). Write a function which takes a 2-dimensional array as input, and outputs an HTML table that looks like the table below (namely, it prints the top row with the given attribute names, and then the rows of the array). Your main PHP program should output sub-arrays from the input array such that each sub-array has only the data for a particular loan (e.g. there will be an array of three rows for L17). Call the print_table function once for each sub-array and display the output via the web client. customer loan_no amount branch_name 111-12-0000 L17 1000 Downtown 222-12-0000 L23 2000 Redwood 333-12-0000 L15 1500 Pennyridge 444-00-0000 L93 500 Mianus 666-12-0000 L17 1000 Downtown 111-12-0000 L11 900 Round Hill 999-12-0000 L17 1000 Downtown 777-12-0000 L16 1300 Pennyridge Step 4. Working with strings: Regular expressions. When working with web-based applications and DB, you will often be processing data in the form of strings of characters. Regular expressions (RegExps) are a very powerful method to do pattern matching on strings. Many string functions use RegExps.
  • 4. <?php // Define a string $text = "Never let a fool kiss you, never let a kiss fool you"; echo "Text is: $text <br>n"; // Two ways to search for a constant string in a long string: // strstr( ), and preg_match( ) // Notice how the ‘’ is used to escape the "-mark in the argument of echo. if ( strstr( $text, "fool") ) { echo "strstr: Found "fool" in text <br>n";} if ( preg_match( "/fool/", $text) ) { echo "preg_match: Found "fool" in text <br>n";} // preg_match_all( ) can be used for case-insensitive search, // and multiple matches // In the RegExp, the pattern to match is between the /…/ // the ‘i’ at the end indicates that the match should be case-insensitive $no_of_hits = preg_match_all( "/never/i", $text, $matches); echo "preg_match_all: Found $no_of_hits instances of "never" in text; they were: "; for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; } echo "<br> n"; // to catch all instances of ‘fool’ or ‘kiss’, use the ‘|’ in the RegExp $no_of_hits = preg_match_all( "/fool|kiss/", $text, $matches); echo "preg_match_all: Found $no_of_hits instances of "fool" or "kiss" in text; they were: "; for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; } echo "<br> n"; ?> What you learnt: 1. Regular expressions are in fact a very powerful concept; we only saw the simplest RegExps. You will see many other uses in future labs – you can use RegExps to search for very complicated and patterns. Exercise: Write a CGI program that will receive the abstract of a paper submitted by a form via a web client. Your CGI program should search for the following incorrectly spelt words in the abstract. It should then return the same text to the web client, except that all the incorrectly spelt words should be colored in red, and the corrected spelling is suggested in brackets, in blue color. List of incorrect spellings to check: teh the Teh The acn can
  • 5. abotu about actualyl actually For example, if the input text is: Teh quick brown fox acn jump over the lazy fox. Then the output should be: Teh [do you mean: The] quick brown fox acn [do you mean: can] jump over the lazy fox. References: 1. HTML quick reference file. 2. PHP tutorials and function references: (from www.php.net) 3. PHP tutorial site: http://www.w3pop.com/learn/view/p/3/o/0/doc/php_ref_string/ 4. Another PHP tutorial/reference: http://www.w3schools.com/PHP/php_ref_array.asp Lab materials for IELM 511 prepared by WEI Xiangzhi, Dept of IELM, HKUST.