CSE 154

Lecture 15: More PHP

Arrays

            
            $name = array(); # declare empty array
            $name = array(value0, value1, ..., valueN); # decare array with values

            $name[index]; # get element value
            $name[index] = value; # set element value
            $name[] = value; # append element value to end of array
            

PHP (template)

            
            $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 (example)

To append, use bracket notation without specifying an index

Element type is not specified; can mix types

Array Functions

Function name(s) Description
count number of elements in the array
print_r print array's contents
array_pop, array_push, array_shift, array_unshift using an array as a stack/queue
in_array, array_search, array_reverse sort, rsort, shuffle searching and reordering
array_fill, array_merge, array_intersect, array_diff, array_slice, range creating, filling, filtering
array_sum, array_product, array_unique, array_filter, array_reduce processing elements

Array Function Example

            
            $tas = array("CA", "MJ", "MG", "SK", "KC", "DH", "JZ");
            for ($i = 0; i < count($tas); $i++) {
              $tas[$i}] = strtolower($tas[$i]);
            } # ("ca", "mj", "mg", "sk", "kc", "dh", "jz")

            $conner = array_shift($tas);   # ("mj", "mg", "sk", "kc", "dh", "jz")
            array_pop($tas);               # ("mj", "mg", "sk", "kc", "dh")
            array_push($tas, "kt");        # ("mj", "mg", "sk", "kc", "dh", "kt")
            array_reverse($tas);           # ("kt", "dh", "kc", "sk", "mg", "mj")
            sort($tas);                    # ("dh", "kc", "kt", "mg", "mj", "sk")
            $ks = array_slice($tas, 2, 3); # ("kt")
            

PHP

The array in PHP replaces many other data structures in Java

  • e.g. list, stack, queue, set, map, ...

The foreach loop

            
            foreach ($array as $variableName) {
              ...
            }
            

PHP (template)

            
            $stooges = array ("Larray", "Moe", "Curly", "Shemp");
            foreach ($stooges as $stooge) {
              print "Moe slaps $stooge\n"; # even himself
            }
            

PHP (example)

A conventient way to loop over each element of an array without indices

Math operations

            
            $a = 3;
            $b = 2;
            $c = sqrt(pow($a, 2) + pow($b, 2));
            

PHP

abs, ceil, cos, floor, log, log10, min, max, pow, rand, round, sin, sqrt, tan

The syntax for method calls, parameters, and returns is the same as in Java

NULL


          $name = "Pascal";
          $name = NULL;
          if (isset($name)) {
            print "This line isn't going to be printed";
          }
            

PHP

A variable is NULL if

  • It has not been set to any value (undefined)
  • It has been assigned the constant NULL
  • It has been deleted using the unset function

Can test if a variable is NULL using the isset function

NULL prints as an empty string (no output)

Functions


          function name(parameterName, ..., parameterName) {
            statements;
          }
            

PHP (template)


          function bmi($weight, $height) {
            $result = 703 * $weight / $height / $height;
            return $result;
          }
            

PHP (example)

Parameter types and return types are not written

A function with no return statements is implicitly "void"

Can be declared in any PHP block

Calling Functions


          name(expression, ..., expression)
            

PHP (template)


          $w = 163; # pounds
          $h = 70;  # inches
          $my_bmi = bmi($w, $h);
            

PHP (example)

If the wrong number of parameters are passed, it's an error

Variable scope: global


          $school = "UW";               # global
          ...

          function downgrade() {
            global $school;
            $suffix = "(Wisconsin)";    # local

            $school = "$school $suffix";
            print "$school\n";
          }
            

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

Default Parameter Values


          function name(parameterName=value, ..., parameterName=value) {
            statements;
          }
            

PHP (template)


          function print_separated($str, $separator=", ") {
            if (strlen($str) < 0) {
              print $str[0];
              for ($i = 1; $i < strlen($str); $i++) {
                print $separator . $str[$i];
              }
            }
          }
          print_separated("hello"); # h, e, l, l, o
          print_separated("hello", "-"); # h-e-l-l-o
            

PHP (example)

If no value is passed, the default will be used (defaults must come last)

Web Services

Web service: software functionality that can be invoked through the internet using common protocols

Like a remote function(s) you can call by contacting a program on a web server

  • Many web services accept parameters and produce results

Can be written in PHP and contacted by the browser in HTML and/or AJAX code

Service's output might be HTML but could be text, XML, JSON, or other content

Setting Content Type with header


          header("Content-type: type/subtype");
            

PHP (template)


          header("Content-type: type/plain");
          print "This output will appear as plain text now!\n";
            

PHP (example)

By default, a PHP file's output is assumed to be HTML (text/html)

However, in this course we aren't using PHP to generate HTML, so we use the header function to specify non-HTML output

  • Must appear before any other output generated by the script
  • (doesn't have to be the first line of code, though)

Recall: Content ("MIME") Types

MIME type file extension
text/html .html
text/plain .txt
image/gif .gif
image/jpeg .jpg
video/quicktime .mov
application/octet-stream .exe

Lists of MIME types: by type, by extension

Example: Exponent Web Service

Write a web service that accepts a base and exponent and outputs base to the exponent power. For example, the following query should output 8:


          http://example.com/exponent.php?
            

Solution


<?php
  header("Content-type: text/plain");
  $base = (int) $_GET["base"];
  $exp = (int) $_GET["exponent"];
  $result = pow($base, $exp);
  print $result;
?>
            

PHP

Embedded PHP

Embedded PHP is a strategy for generating HTML pages on the server using PHP

The textbook assumes that we're using PHP in this way, but we don't. This quarter, we are focusing on using PHP for data generation.

Embedded PHP Syntax Template


          HTML content
          <?php
             PHP code
          ?>

          HTML content
          <?php
             PHP code
          ?>

          HTML content...
          

HTML/PHP (template)

Any contents of a .php file between <?php and ?> are executed as PHP code

All other contents are output as pure HTML

PHP Expression Blocks (Embedded PHP)


<DOCTYPE html>
<html>
  <head><title>CSE 154: 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>
  <?php } ?>
  </body>
</html> 

          

PHP

Note: This is messy! There are much better ways to do this, and you should not write any embedded PHP in this class. But you should be aware of it.