Workshop in Computational Bioskills - Lesson 9

Workshop in Computational Bioskills - Spring 2008

Lesson 9 - Building a Dynamic web site 

Building a website is done in HTML : For a short introduction to HTML click here

Building a dynamic website requires a bit more...

PHP Basics Introduction Variables Arrays Control Flow


PHP - Dynamic Web Pages Language

PHP: Hypertext Preprocessor programing language, used for writing
dynamic web pages, when the page content depends on the input given by the user.

Several facts on PHP


Why PHP?

Getting Started

File Hello_world.php: 

<html>
<head>
    <title> PHP Hello </title>
</head>
<body>
  <b>
    <? print "Hello World!" ?>
  </b>
</body>
</html>

But that was not really dynamic (why?).
Let's see for example how to create a simple_form.php
(recall how to write forms).
We will revisit this example later on. First let's continue with the basics...


Scalar Variables PHP has two data types: strings and numbers.

o Like the perl scalars (denoted by the "$" sign).
o Naming convention - letters, underscore and numbers
  (not in the beginning).
o Arithmetic operations permitted: just like in perl.

Numbers 
Not much to say here - just like in perl and other languages.
Boolean
false is represented by the empty string, empty array and the number zero.
Strings

Strings appear in three formats: 
Single quotes: <? print 'That\'s your name: $name' ?> // That's your name: $name
Double quotes: <? print "Your name is $name" ?> // Your name is Dani
Strings with more than one line are done with Here-document (Heredoc) 
syntax:

 <? print  
<<< HTMLBLOCK
<html> 
  <body> 
    some text...
  </body> 
</html>     
HTMLBLOCK;
?>  

Prints all the text between the HTMLBLOCK tags
o Variables inside strings: $preparation = '
Braise'; $meat = 'Beef'; print "{$preparation}d $meat with Vegetables"; // Braised Beef with Vegetables Variable Comparison
  • Use '==' to compare variables
  • strings are compared lexicographically
  • strings that contain numbers are sometimes compared as strings and sometimes as numbers, depends on the compared variable
  • strcmp() - always compare as strings, therefore ("54213" < "56") returns false, but strcmp("54213","56") return -1, i.e. 56 is greater than 54213.
  • There are many useful functions on Strings:
    • trim( $string ) removes whitespace from the beginning and end of a string.
    • strlen( $str ) returns the length of the string.
    • printf( format, $str ) formated print, like in C and Perl.
    • strcasecmp( $str1, $str2 ) compares the strings, case insensitive.
    • strtolower( $str ) and strtoupper( $str ) - change the string to be all lower case or upper case.
    • ucwords( $str ) upper case the first letter of each word in the string
    • substr($str, offset, length) extract length number of chars from the string, starting in offset. If offset is negative, it is defined from the end.
    • str_replace( $substr, $rep, $string ) replace each appearance of $substr with $rep
    Let's see a simple example for manipulating text.

    Arrays
    
    o The definition of Arrays in PHP includes both lists (associative
      arrays) and hashes, where the list is a specific case of an hash.
    o The name of the hash/list is a regular variable name - beware
      not to override existing variables. 
    o The array keys must be scalar (string or number), and the
      array elements can be either scalars or arrays.
    o An array is created by the array() construct.
    
    Associative Array (Hash) Declaration:
    
    By calling the constructor: 
    
    $vegetables = array( 'corn' => 'yellow', 
                        'carrot' => 'orange',
                        'tomato' => 'red' );
    
    The keys can be numbers, string or both. 
    
    Or by a direct assignment: 
    
    $vegetables['corn'] = 'yellow';
    $vegetables['carrot'] = 'orange';
    $vegetables['tomato'] = 'red';
    
    $dinner[0] = 'chicken';
    $dinner[1] = 'rice';
    
    $price['perl book'] = 29.99;
    $price['php book'] = 25.0;
    
    
    List Declaration:
    
    When the keys are ordered integers, the hash is very much like an
    ordered list. PHP has a shortcut to generate a list: 
    
    
    $dinner = array('chicken', 'rice');
    print "$dinner[1]"; // rice
    
    
    
    In fact...
    
    // This array ...
    array(1 => "Peter", "paul", "Mary", "Peter"=>"Jan");
    
      // ...is the same as this array
    array(1 => "Peter", 2 => "paul", 3 => "Mary", "Peter"=>"Jan");
    
    
    


    Array Operations
    
    o An array element can be manipulated like a regular variable: 
    
    
    $dinner[1] = 'potato'; // assignment
    
    $cost = $price['perl book'] + $price['php book']; //arithmetic operations
    
    unset( $price['perl book'] ); // removes the element from the array.
                                  // It is different from 
    			      // setting the value to zero or to empty string 
    
    
    o $arr[] - add a new element to the end of array: 
    
             $dinner[] = 'ice-cream'; // $dinner[2] is now 'ice-cream'.
    
    
    o count( $arr ) - return the number of elements in the array.
    
    
    o foreach($arr as $key=>$value) - iterate over the hash
    elements: 
    
    foreach ($vegetables as $veg=>$color)
    {
    // the values are copied to $veg and $color
     // therefore changing their values does not affect the list.
     print "<tr><td>$veg</td><td>$color</td></tr>\n";
    }
    
    
    o foreach($arr as $value) - shortcut for lists:  
    
    foreach ($dinner as $dish)
    {
     print "going to eat $dish\n";
    }
    
    
    Note: The element are accessed in the order they were added to the 
    array. if you want to access them with index order, use a standard for() loop. 
    
    o Finding an element in the array: 
    
    // array_key_exists looks for the given key in the array and 
    // returns true or false; 
    
    if (array_key_exists('corn',$vegetables))
    { 
     print "yes, we have corn\n"; 
    }
    
    
    // in_array looks for the given value in the array and 
    // returns true or false. The search is case sensitive:
    
    if (in_array('red',$vegetables)
    {
     print "yes, we found something red in the vegs list\n"; 
    }
    
    
    // array_search looks for the given value in the array and 
    // returns its key.
    
    $key = array_search('red',$vegetables);
    if ($key)
    {
     print "the red vegetable is: $key\n";
    }
    
    
    o implode($delim, $arr) -
    print of the value list (like perl join).
    
    print "<tr><td>".implode("</td><td>",$dinner)."</td></tr>";
    
    o explode($string) - split string into an array.
    
    $colors = 'red, white, blue, green';
    
    $color_list = explode(', ',$colors);
    
    


    Array Sorting

    Lexicographic ordering of the array elements:
    • sort() - sorts lists values (increasing) Remove the keys therefore it is not good for sorting hashes
    • asort() - sorts hashes according to their values. Keeps the associated keys.
    • ksort() - sorts hashes according to their keys.
    • rsort(), arsort(), krsort() do the same but with decreasing order of the elements


    Multidimensional Arrays
    The value of an element can be itself an array. 
    
    // Declaration
    
    $prices =  array(
               'red' => array('apple'=> 7.00, 'tomato'=> 4.30 ),
    	   'green' => array('letus' => 2.00,'cucumber' => 3.5),
    	   'yellow' => array('corn' => 10.00 ,'lemon' => 5.05 ) );
    
    // Now let's print it:
    
    print $prices['red']['tomato']; // 4.30
    print $prices['green']['cucumber']; // 3.5
    
    
    

    Control Flow
    Similar to c and perl: if, elseif, else, switch, while, do...while, for, foreach
    Go to more advanced PHP programming