Workshop in Computational Bioskills - Lesson 11

Workshop in Computational Bioskills - Spring 2006

Lesson 9 - PHP Basics

Introduction
Variables
Arrays
Control Flow



PHP - Dynamic Web Pages Language PHP - programing language, used for writing dynamic web pages, when the page content depends on the user input.

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. If you want, recall how to write form in Lesson 7.


Strings
PHP has two data types: strings and numbers.

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 Dubi

Here-document (Heredoc) syntax:

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

Prints all the text between the HTMLBLOCK tags
Useful string functions
  • 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

Numbers
No 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.

Variables

o Like the perl scalars.
o Naming convention - letters, underscore and numbers (not in the beginning).
o Arithmetic operations permitted: just like perl.
o Variables inside strings: 

$preparation= 'Braise';
$meat = 'Beef';
print "{$preparation}d $meat with Vegetables"; // Braised Beef with Vegetables