Introduction to PHP

From Wikiversity
Jump to: navigation, search

PHP (recursive acronym for "PHP: Hypertext Preprocessor"—formerly the acronym for "Personal Home Page") is a server-side scripting language designed for use in web based applications. As it is a server side scripting language, its use requires a web server installed, configured and enabled with PHP.


This is a course designed to teach PHP by example (and eventually assignment) to anyone willing to learn. Bear in mind that this course is still a work in progress and is by no means comprehensive in its current state. In addition, it is fairly fast paced and it is suggested participants utilize various other learning resources to assist them in their learning.

If you feel that a certain section lacks detail, or there is a blatant error in a statement, change it! Alternatively, point it out on the talk page and an experienced user will take a look at it.

For a more complete tutorial, visit:


Basic Syntax[edit]

When PHP parses a file (web servers are generally configured to have PHP parse files with the .php extension), it looks for an opening tag and a closing tag and then interprets the code between the two:

echo 'This is being parsed.';
This is not being parsed.

PHP will output everything that is not contained within an opening tag (commonly <?php, but could also be <? or <script language="PHP">, however the shorter <? tag is no longer recommended as it conflicts with XML opening tags) and a closing tag (?> or </script>) exactly as it is written. All statements in PHP should end with a semicolon; most of the time only one statement will occur on each line. This denotes to the PHP interpreter that the statement it has read is complete and that it should anticipate the next (or the ?> tag or EOF, end of file). This is because different text editors handle new lines differently.

The Notepad utility on Microsoft Windows is notorious for being terrible with UNIX end of line compatibility. This is because Notepad expects \r\n, both a newline and a carriage return, while UNIX-based systems only insert the \n newline character. Notepad will open a UNIX-style text file and show the "empty box" unrecognized character instead of the expected line break. Using a more advanced text editor will alleviate these conflicts; the UNIX style produces a smaller script file because each newline only requires 2 bytes (one character) to break the line instead of 4 bytes. For large files, this could make a difference but only as far as storage on your server goes, because the PHP code is never sent to the user's browser, only the result of the PHP commands that were executed; the user will get nothing more than HTML, ideally.

Terminating statements with the semicolon allows coders to squeeze together small blocks of code on the same line. For example, the following is acceptable:

<?php $m='This is being parsed';echo $m; ?>

And will work just the same as the example below. Even though this code will be interpreted correctly by the server, it is generally considered poor style


see also Variables

Variables are locations in memory where information is stored. PHP scripts can contain variables, which are denoted with the $ at the start of their unique identifier (two variables with the same identifier are, essentially, the same variable). Unlike many low end languages, variables in PHP need not be declared and defined—when a variable is used, PHP automatically creates it and assigns it a null value if it does not already exist. Take a look at this example:

$message = 'This is being parsed.';
echo $message;

Notice the difference from the first example—in this, we assign the sentence This is being parsed. to the variable $message and then output it. This may seem like a pointless example, but rest assured, variables have a very important purpose in PHP. In addition, variables in PHP are not statically typed, meaning that there is only one generic type for scalar values (numbers and strings), and another 2 types for aggregate structures (arrays and hashes ("associative arrays")).


An array is a special variable that stores one or more values in a single variable. If you have a list of items, storing them in single variables could look like this:

$item1="item-name1"; $item2=" item-name2"; $item3=" item-name3";

An array can hold all your variable values under a single name and you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays (PHP tutorial to learn more about kinds of arrays):

  • Numeric array – An array with a numeric index
  • Associative array – An array where each ID key is associated with a value
  • Multidimensional array – An array containing one or more arrays

Alternatively, Arrays can be defined like a set of variables and values, combined together under one common name. For example, if we have 3 variables:

$fruit = 'banana';
$vegetable = 'cabbage';
$dessert = 'rasgulla';  // "rasgulla" is an Indian sweet dish.

An array can be made with these three variables and their values with a more common name like "eatables". So if we create an array, it will be something like:

$eatables['fruit'] = 'banana';
$eatables['vegetable'] = 'cabbage';
$eatables['dessert'] = 'rasgulla';


$eatables = array( 'fruit'=> 'banana', 'vegetable' => 'cabbage', 'dessert' => 'rasgulla');

Now, as discussed above, the 3 kinds of arrays in PHP are as follows this:

1. Numeric array: the array with numeric index. Example:

  $users = array(
                  0 => 'albert',
                  1 => 'john',
                  2 => 'cindy',
                  3 => 'cobbel',

To access users from this array, we use: $users[0], $users[1] & so on. Hence this is called a numeric array.

2. Associative array: array with strings as the index. Example:

  $eatables = array(
                    'fruit'=> 'banana',
                    'vegetable' => 'cabbage',
                    'dessert' => 'rasgulla'

To access data, we use: $eatables['fruit'], $eatables['vegetable'] etc. Thus eatables is an Associative array where a meaningful or non-meaningful string (variable name) is associated with each value.

3. Multidimensional array: an array of arrays. Example:

  $food = array(
                 'fruits' => array(
                                   0 => 'banana',
                                   1 => 'orange',
                                   2 => 'apple'
                 'vegetables' => array(
                                       0 => 'cabbage',
                                       1 => 'carrot',
                                       2 => 'potato'

To access 'banana', you refer to $food['fruits'][0], or for 'carrot', you use $food['vegetables'][1]. Thus food has more than 1 dimension (or level), and is a multidimensional array. The only limit to the number of dimensions is the size of the memory stack available to your program. (The same goes for the number of elements to an array.)


see also Constants

Constants are generally immutable (unchangeable) values supplied by the PHP execution environment. They are used to pass various bits of information which might be useful at runtime. To see what some of these constants and "environment variables" are, create a file named phpinfo.php on your PHP web server with the following contents:

<?php phpinfo(); ?>

This will also give other information about your system. Note that most of the environment variables are given in a special associative array, $_SERVER


Strings in PHP can be specified in one of two ways.

  • String literals—single-quoted strings:
$myString = 'this is a \n literal string'; //an echo will print: this is a \n literal string
  • Normal strings—double-quoted strings:
$myString = "this is a\nnormal string";
/* output is:
   this is a
   normal string

Using normal strings, the preprocessor will also parse any variable names that are encountered, substituting their value:

$a = 54;
$myString = "Age is $a";
echo $myString; //Age is 54
echo "Age is $a"; //Age is 54

Escaping Strings[edit]

Depending on how you have declared a string, and how the data in the string is formatted, it may be necessary to escape certain characters. Take the following code, for example:

$str = "Grandpa Don't touch me, he cried";
$str2 = 'Grandpa Don't touch me, he cried';

There is no problem with the declaration of $str, but PHP will throw an error upon encountering the $str2 declaration. Can you see why this is?

As far as PHP is concerned, the contents of $str2 stopped when it encountered the second ' (single quote). After that, the interpreter found some stray characters followed by an orphan ' (single quote) with no closing quote.

To overcome this problem, we use PHP's escape character, the backslash.

$str2 = 'Grandpa don\'t touch me, he cried';

The above variable declaration is now valid.

Escaping can also be used when wanting to output a special character, such as \n (newline), in a Normal String Declaration. Can you think of a way we could escape \n to allow us to output '\n' as opposed to a newline?

Of course, it is exactly the same as escaping the single quote, we apply a backslash to \n, turning it into \\n, thus escaping the initial backslash that was portraying it as a special character, and representing it literally.


PHP supports commenting code for ease of viewing by humans. There are two common ways of commenting: comment blocks and line commenting.

Comment blocks[edit]

Comment blocks work by denoting a range from one point to another within a script as a comment, which is then ignored entirely by the PHP interpreter. They can be inserted anywhere (although it is good practise to give them their own few lines in the script for readability's sake) and are denoted by two special characters: / and *. Take a look at this example:

/* This is a comment. */
echo 'This is being parsed.';

Notice that the order of the / and * alternate. To designate an area in a script as a comment block, simply begin it with a /* and end with a */. Comments can, as mentioned above, be placed anywhere like this:

/* This is a comment. */
echo /* This is also a comment */ 'This is being parsed.';
ec/* Depending on server configuration, this may or may not work. Check your PHP manual
for details.*/ho '/*This is another oddly placed comment block. To actually display this in PHP,
you would need to use the break character, which will be outlined in future lessons. */
This is being parsed.'/* And once again, this is a suspiciously placed comment,
but should not make any difference to the script. */;

Notice that comment blocks are placed between the echo function and its parameters, within the function call for echo itself (ec/* ... */ho), within the string passed to the echo function and just before the end of line declaration (with the semicolon).

Line commenting[edit]

Line commenting is much like the comment block, except that it only affects a particular line from a given point onwards, cannot be ended until the next line and uses the // or # operator. Examine the following example:

// This is a comment. echo 'This will NOT be parsed.';
# This is also a comment. echo 'This will also NOT be parsed.';
echo 'This will be parsed.';

Anything after a // on a line is considered a comment, ignored entirely by the interpreter and meaningless to anything but a human examining the code. Remember that the use of echo 'This will NOT be parsed.'; above is totally immaterial; the word echo will not be treated as a function call. A // can also be added to the end of a line (must be after the semicolon if there is a function call on the same line) and anything after it will be commented, like so:

echo 'This will be parsed.'; // This will not be parsed.
echo 'This will be parsed.'; # This will not be parsed.

Functions and arguments[edit]

PHP is well known for its extensive library of built-in functions. A function in PHP is a set of code predefined to be called by a particular keyword, either built into PHP's numerous libraries, or defined by the person writing the script within the code. A function can be declared like this:

function echostuff() {
    echo 'Stuff';

In the same script, the function can then be called like this:


This will output 'Stuff' (without the quotation marks). Functions can have arguments which can be passed when the function is called. An argument is a variable that you pass directly to the function. Here is an example of a simple function that takes a name as an argument, and outputs a nice greeting:

function greet($name) {
    echo 'Hi ' . $name;

Note the use of the period here, between "'Hi '" and "$name". This will concatenate the two variables together.

We can call this function in a couple of ways, either by passing a defined variable to it:

 $name = 'John Doe';

Or, we can just pass the name directly to the function, also called a 'literal string':

 greet('John Doe');

Finally, we can also pass multiple arguments to a function. To do this, just separate each variable with a comma:

 function greet($name, $day) {
     echo 'Hi ' . $name . ', how are you doing on this fine ' . $day . '?';
 greet('John Doe', 'Tuesday');


Nuvola apps ksig.png Type classification: this is a homework assignment resource.

Now it's your turn to get your hands dirty! Create a function that takes a name, an age, and a height, and outputs a sentence using all of these variables. Also, call the function using a combination of variables and literals.

Check your answer here: PHP Assignment Answers, and remember, in programming there are a thousand ways to do anything, so don't worry if your script doesn't exactly match the answer! Just make sure it works.

Learning Sessions[edit]

See also[edit]