Introduction To PHP
Introduction To PHP
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.
Contents
[hide]
• 1 Introduction
• 2 Prerequisites
• 3 Basic Syntax
o 3.1 Variables
3.1.1 Arrays
o 3.2 Constants
o 3.3 Strings
o 3.4 Comments
• 4 Assignment
• 5 Learning Sessions
• 6 See also
[edit]Introduction
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.
[edit]Basic Syntax
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:
<?php
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 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:
<?php
$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")).
[edit]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:
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):
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';
OR
$eatables = array( 'fruit'=> 'banana', 'vegetable' => 'cabbage', 'dessert' => 'rasgulla');
Now, as discussed above, the 3 kinds of arrays in PHP are like this:
$users = array(
0 => 'albert',
1 => 'john',
2 => 'cindy',
3 => 'cobbel',
...
);
To access users from this array, we use: $users[0], $users[1] & so
on. And hence they are called numeric arrays.
$eatables = array(
'fruit'=> 'banana',
'vegetable' => 'cabbage',
'dessert' => 'rasgulla'
);
To access data, we use: $eatables['fruit'], $eatables['vegetable']
etc. So they are called Associative array where a meaningful
or non-meaningful string (variable name) is associated with each
value.
$food = array(
'fruits' => array(
0 => 'banana',
1 => 'orange',
2 => 'apple'
),
'vegetables' => array(
0 => 'cabbage',
1 => 'carrot',
2 => 'potato'
),
);
So here, to access 'banana', you need to refer as $food['fruits'][0],
or for 'carrot', you need $food['vegetables'][1].
That means its more than 1 dimension, you can have any level of
dimension, and the concept is called multidimensional array.
[edit]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:
This will also give other information about your system. Note that most of the environment variables
are given in a special associative array, $_SERVER
[edit]Strings
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
[edit]Escaping Strings
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:
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), and then the interpreter has the found some stray characters after the ' (single quote),
generating an error.
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.
[edit]Comments
PHP supports commenting code for ease of viewing by humans. There are two common ways of
commenting: comment blocks and line commenting.
[edit]Comment blocks
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:
<?php
/* 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:
<?php
/* 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).
[edit]Line commenting
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 only uses the // operator. Examine the
following example:
<?php
// This is a comment. echo 'This will 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:
<?php
echo 'This will be parsed.'; // This will not be parsed.
?>
[edit]Functions and arguments
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:
<?php
function echostuff() {
echo 'Stuff';
}
?>
In the same script, the function can then be called like this:
<?php
echostuff();
?>
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:
<?php
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:
<?php
$name = 'John Doe';
greet($name);
?>
Or, we can just pass the name directly to the function, also called a 'literal string':
<?php
greet('John Doe');
?>
Finally, we can also pass multiple arguments to a function. To do this, just separate each variable with
a comma:
<?php
function greet($name, $day) {
echo 'Hi ' . $name . ', how are you doing on this fine ' . $day . '?';
}