Starting with PHP

Andres Baravalle

Starting with PHP

  • Introduction to PHP
  • Lexical structure
  • Variables, constants and operators
  • Conditionals and iteration

Introduction to PHP

Lecture vs practical

During the lecture, we will cover the theoretical material. During your practical session, you will have to come back to the slides and work through the practical activities.

Please keep in mind that during most weeks we will cover only half of our set of lecture slides. That means that in weeks 3 & 4 we are going through the slides for lecture 2.

What is PHP?

  • PHP (PHP: Hypertext Preprocessor) is an Open Source, server-side web development language
    • PHP is an interpreted language, supported by all the most popular web servers, including Apache, IIS, Nginix and LightHTTPD
    • PHP can be also used to write command-line scripts
  • PHP is installed on more than 244 million websites and 2.1 million web servers (January 2013)
PHP logo

What is PHP (2)?

  • Runs on multiple platforms
  • Includes over 150 documented extensions (as of PHP 5.6).
  • Connects to 20+ databases
  • Supports OOP

Features of PHP

  • Authentication and Sessions
  • Cookies
  • Dealing with forms and file uploads
  • Using remote files

PHP scripts

PHP scripts typically include a mix of HTML and PHP code.

PHP code is interpreted by a server, that takes PHP as an input and typically returns HTML code as an output (but you can use PHP to create binary data too!).

A neat separation of PHP code from HTML code (e.g. using functions or Object Oriented approaches) is favorable.

When should you use PHP?

Anytime - or never. In most cases, the software that you use to write your web pages will be depending from a number of issues, as:

  • The operating system that you are using
  • The web server that you are using
  • The database server you are using
  • Any applications that you are using

Common stacks

  • Linux, Apache, MySQL and PHP
  • Windows, IIS, SQL server and ASP.NET
  • Linux, Tomcat, MySQL and Java

Different combinations are less preferred (e.g. Windows, Apache, MySQL and PHP).

Lexical structure

Lexical structure of PHP

In the next slides we are going to understand the lexical structure of PHP (that is, the meaning of its terms).

Learning the lexical structure means understanding the elements that are used when creating scripts with PHP.

Activity #1: Hello World

Let's create our Hello World in HTML 5 + PHP:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Hello World</title>
    </head>
    <body>
    <?php echo "Hello World"; ?>
    </body>
</html>

Save the file as hello.php in your Apache root (htdocs) and open the URL with your browser at http://localhost/hello.php. Root folder and URL vary depending on settings (e.g. whether you are using your localhost or uploading to mastodon).

See the expected output here.

Inserting PHP code

There are a number of different ways to embed PHP code in your page.

The most common is to insert the code inside a <?php ... ?> section:

<?php 
echo "Hello World"; 
?>

Semicolons

A PHP program is quite simply a sequence of instructions made up of symbols (such as keywords, characters with special meaning, numbers, and text chunks) to which the language associates a special meaning.

Simple statements in PHP are typically followed by a semicolon (;):

$x = 1; 
$y = 2;

Inserting comments

Commenting your code leads to code that is more maintainable and easier to read for yourself and for others who may need to modify your code later. Comments also allow you to leave yourself reminders of why you have implemented something in a particular way and provide a mechanism to help with the debugging process by making chunks of code 'invisible'.

PHP comments

Just as HTML comments are ignored by the web browser, the PHP parser recognizes and ignores content appearing as PHP comments in any of the three following styles:

// This is a basic one-line PHP comment
/* This is a C-style PHP comment that can 
	span  multiple lines.  */
# This is a "shell-style" PHP  one-line comment 

Whitespace

Whitespace (spaces, tabs and newlines) can be used freely to format and indent the code. PEAR coding guidelines suggest to use an indent of 4 spaces, with no tabs.

Case sensitivity

Computer languages can be case sensitive or case insensitive (or may be a combination of both).

PHP is case sensitive, which means that the name of keywords and all other language identifiers must always be typed with the correct capitalisation.

Variables, constants and operators

Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; 
?> 

Variable types

PHP supports 8 primitive types for variables:

  • boolean
  • integer
  • float (floating-point number, aka double)
  • string
  • array
  • object
  • resource
  • NULL

Activity #2: using echo

echo the following text in the browser:

So, so you think you can tell
Heaven from Hell,
blue skies from pain.
Can you tell a green field
from a cold steel rail?

by storing the text and HTML (don't forget <blockquote>!) in a variable and then printing the variable.

Strings and escaping

A simple string in PHP is written in double or single quotes and the full-stop operator '.' can be used to concatenate strings.


$a = 'a';
$verb = 'is';
echo $a . " ". $verb . " $a string";

The echoed string here has double quotes and contains a number of variable names. When printing a string enclosed in double quotes, PHP will substitute the variable names with their values, giving us:

a is a string

Escape sequences

Double-quoted strings allow escape sequences.

Here are some common escape sequences:

\"

Double quotation marks

\n

New line

\r

Carriage return

\t

Tab

\\

Backslash

\$

Dollar sign

Escape sequences: new lines

Linux, MacOS and OS X and Windows all use different characters for new lines:

  • \n in Linux
  • \r in Mac OS and OS X
  • \r\n in Windows

Using new line characters and tabs when writing HTML with PHP allows to produce neater HTML code and can make debugging easier.

Escape sequences: new lines (example)

<?php
echo "<ul>\n\t<li>Apple</li>\n\t<li>Pear</li>\n</ul>";
?>

Activity #3: Escaping strings

An extract from Pulp Fiction's script has been redacted to remove inappropriate language - replacing a couple of words with $ signs:

You ain't got no problem, Jules. I'm on the $$$$$$$$$$$$. Go back in there, chill them $$$$$$$ out and wait for the Wolf who should be coming directly.

Assign the text to a variable and print it's value on the screen. Remember to escape special characters as needed.

Predefined variables

PHP provides a large number of predefined variables. Some of the most used are:

  • $_SERVER: Array including server and execution environment information
  • $_GET: An associative array of variables passed to the current script via the URL parameters
  • $_POST: An associative array of variables passed to the current script via the HTTP POST method.

$_SERVER example

<?php
print_r($_SERVER);
?>

See the expected output here.

$_GET example

<?php
echo 'Hello ' . $_GET["name"] . '!';
?>

Assuming the user entered http://example.com/?name=Andres

The above example will output something similar to:

Hello Andres!

Activity 4: printing POST variables

First, create a simple page (lecture2_form_target.php) that will be used as a target for a form submission.

Include this code in the page:


<?php
print_r($_POST);
?>            

Now create a new page (lecture2_form.html) including a simple form with a input line.

Change the action attribute of your form tag to use lecture2_form_target.php as a target.

Test the results.

Variable variables

A variable variable is a variable having the value of another variable as name.

<?php
$a = "hello";
$$a = "world";
echo "$a ${$a}"; // prints 'hello world'
echo "$a $hello"; // prints 'hello world'
?>

Constants

A constant can be defined by using the define() function or by using the const keyword inside a class definition. Once a constant is defined, it can never be changed or undefined.

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT;
?>  

Operators

In PHP, operators are special functions that operate on one to three values (operands).

The most common operators require one operand (unary operators) or two operands (binary operators).

Unary operators require a single operand, which can be before or after the operator. Binary operators require two operands, one before and one after the operator.

By now you have seen the assignment operator (‘=’).

PHP includes a large number of operators (more than 30), but we are going to focus only on some.

Summary of the main PHP operators (1)

Arithmetic operators $a + $b
$a - $b
$a * $b
$a / $b
Incrementing and decrementing $a++ (post-increment)
$a-- (post-decrement)
++$a (pre-increment)
--$a (pre-decrement)

Summary of the main PHP operators (2)

Assignment operators $a = 12;
Comparison operators $a == $b (equal)
$a === $b (identical - includes type checking)
$a != $b
$a !== $b
$a > $b
$a < $b
$a >= $b
$a < $b

Summary of the main PHP operators (3)

Error control @
Concatenation $a . "world"

Activity #5: Math operators

Use PHP operators and variables to print out the following text:

10 + 7 = 17
10 - 7 = 3
10 * 7 = 70
10 / 7 = 1.4285714285714
10 % 7 = 3

Start by creating the following variables:

$x=10;
$y=7;

and use $x, $y and PHP operators to replicate the text. See the expected output here.

Activity #6

Use arithmetic, assignment and increment operators to manipulate one (and only one) variable to produce the script below.

Value is now 1.
Value is now 10.
Value is now 6.
Value is now 30.
Value is now 10.
Value is now 11.

Start with:

$a = 1;

and keep manipulating $a and printing its value.

Activity #7

Assign a value to $a and to 3 variable variables based on $a so that:

<?php
echo $a . $super . $cali . $fragilistic;
?>

would output "Supercalifragilisticexpialidocious".

You cannot user $super, $cali and $fragilistic, but you have to instead use only $a and variable variables based on $a.

Conditionals and iteration

Operators and type conversions

PHP is generally labeled a ‘loosely typed’ language because variables are just named and used, rather than named and given a type.

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Type casting can be used to convert a variable to a given type:

<?php
$a = "0";  // $a is a string
$b = (boolean)$a // $b is ?
?> 

print_r and var_dump

  • Use print_r to print human readable information about a variable
  • Use var_dump to dump all information on a variable
<?php
$a = "0";
print_r($a);
var_dump($a); 
?>

Activity #8: Testing type conversion

Examine this code:

<?php
$a = "0";  
$a += 2;  
$a = $a + 1.3;  
?> 

What is the type of the variable a in each of those lines?

Use var_dump after each assignment to find if your answer is correct.

Expressions

Programming in any language requires manipulating data. In some cases, the data will be just literals (such as text strings) but quite often more complex expressions will be used. Anything that can be evaluated by the PHP interpreter can be thought of as an expression, just as literals are any data that appear directly in a program.

Expressions can use a number of different operators, or no operators at all.

For example:

 
$a > 2
$a > $b/4
$a           
         

Statements

Statements are PHP instructions that tell the interpreter to perform an action.

You have already seen some examples of statements:

 
$a = "0"; 
$a += 2;  
$a = $a + 1.3;
             

Error messages

When developing an application, it's very unlikely that you will not make some kind of programming error.

Depending on your configuration, PHP might be not be showing any errors. To display the errors, include the following statements at the beginning of your files:

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
?>
            

Conditionals and iteration

Conditional statements

The if statement allows you to test an expression and then make a branch in the script’s flow of control.

if ($a == 1) {
	// if $a is '1'
	// do something
} 

Remember: you can have multiple statements inside an if branch.

Conditional statements (n way decisions)

You can have n way decisions - with different possible branches. Use for your first branch, elseif for your alternative branches and else for the default route.

if ($a == 1) { 
    // if $a is '1'
	// do something
} 
elseif ($a == 2) { 
    // if $a is '2'
    // do something else
} 
else {
        // optional 'catch all' branch
        // statements applicable if $a not '1' or '2'
}             

Conditional statements (nesting)

To obtain multi-way branches you can also use nested if statements: the branch that will be followed during the execution will depend on the value of the expression that is evaluated in the if statement.

if ($a == 1) { 
    // if $a is '1'
	// do something
} 
else {
    if ($a == 2) { 
        // if $a is '2'
        // do something else
    } 
    else {
        // optional 'catch all' branch
        // statements applicable if $a not '1' or '2'
    }
}             

Iteration: for loops

One of the more used loop statements is the for statement. It is used to perform a sequence of one or more instructions a number of times.

The general form of the for loop is:


for ( [initialisation]; [test];  [increment] ) {
    [statement]
}

Iteration: for loops (2)

The loop typically initialises a counter which is then tested against a terminating condition. If the condition is true the statement is then executed and the counter is incremented before repeating the process. The simple example below will output the numbers 0 to 9, one number per line:

for ($a = 0; $a < 10;  $a++) {
    //  we are concatenating the value of $a with
    //  a line break, <br>
    echo $a  . "<br>";
}    

This type of loop is the most common and is called a 'Counter loop'.

Activity #9: Golden ratio pairs

Read the first few lines of the Wikipedia page describing the golden ratio (a ratio vastly used in the arts).

To find a "golden ratio pair", where the first number, a is given, use:

b = (1 + √5)/2 * a

After testing the formula, for all the integers from 1 to 10 ($a), calculate what should be the value of $b so that $a and $b are in the golden ratio.

Note: use sqrt($var) to calculate the square root of a number.

Iteration: for loops (3)

You can also use for loops to navigate through a data structure (e.g. array, object):


<?php
    $animals = array("cat","dog","chicken");
    for ($a = 0; $a < sizeof($animals);  $a++) {
    //  we are writing the name of each animal
    //  and then a line break, <br>
    echo $animals[$a]  . "<br>";
}
?> 

This is also a very common use for loops; it is known as 'Iteration Loop'.

Iteration: for loops (4)

Please note that there may be situations in which you do not need all the elements of the for loop (initialisation, test, increment, statement). For example, this is a valid for loop:

for ($a = 0; $a < 10;) {
    echo $a . "<br>";
} 

In this case, you will need to manipulate $a inside your loop - otherwise you risk having an infinite loop.

You can omit (as needed) any element of the for loop.

Iteration: while loops

Another loop statement is the while loop, which has the form:

while ( [expression] ) {
    [statement]
}

The previous for loop example can be recast as a while loop:

$a = 0;
while ($a < 10) {
    echo $a . "<br>";
    $a++;
}

Activity #10: More golden ratio pairs

Read the first few lines of the Wikipedia page describing the golden ratio (a ratio vastly used in the arts).

For all the powers of 2 from 2 to 100 (2, 4 ... 64), calculate what should be the value of $b so that $a and $b are in the golden ratio.

Note: use pow($base, $exp) to calculate the powers of a number.

Iteration: while loops (2)

The previous example was not a very good use of a while loop, and in this case the original for loop is better.

A while loop is typically more appropriate when the number of iterations for the loop is already known.

Iteration: while loops (2)

while loops are often used for 'Sequence loops'.

Sequence loops are common in science, engineering and finance and rely on generating a sequence of numbers, until a boundary is reached.



<?php
$first = 0; # first Fibonacci number
$second = 1; # second Fibonacci number
echo "$second ";
$current = 0; # third Fibonacci number
$boundary = 100;
while ($current <= $boundary) {
	# current becomes previous, and new current is computed
	$current = $first+$second;
	echo "$current ";
	$first = $second;
	$second = $current;
}
?>

Iteration: while loops (3)

In some cases you may need a 'Loop and half' loop: for example, when a variable is changed inside your loop.

This should have been really been the case for the Fibonacci example.

Activity #11: Better Fibonacci

Read the first few lines of the Wikipedia page describing the Fibonacci numbers.

Update the code in the slide before to calculate the Fibonacci numbers between 1 and a given boundary (=100).

Activity #12: Better Fibonacci

Same as Activity #11, but using a for loop.

This work

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License

Creative Commons License