Anu Sharma: Introduction To PHP, Building Blocks and Flow Control
Anu Sharma: Introduction To PHP, Building Blocks and Flow Control
Anu Sharma: Introduction To PHP, Building Blocks and Flow Control
Anu Sharma
Indian Agricultural Statistics Research Institute, New Delhi – 110012
What is PHP?
PHP stands for PHP Hypertext Preprocessor. Originally, PHP stood for Personalized
Home Pages. In one sentence — PHP is a server-side, HTML-embedded scripting
language.
Brief history
Rasmus Lerdorf conceived PHP sometime in 1994. Early non-released versions were
used on his home page to keep track of who was looking at his online resume. The
first version was available in early 1995 and was known as the Personal Home Page
tools. It came with a simple parser engine that understood only a few special macros
and a number of utilities that were in common use to create home pages back then—a
guest book, a counter, and so on. The parser was rewritten in mid-1995 and named
PHP/FI version 2. The FI came from another package, written by Rasmus, which
interpreted HTML-form data. He combined the Personal Home Page tools scripts with
the Form interpreter and added open source data base MySQL support, and thus was
born PHP/FI. PHP/FI grew at an amazing pace and people started contributing code to
it. Today PHP 5 is available for download.
There are some indisputable great reasons to work with PHP. As an open source
product, PHP is well supported by a talented production team and a committed user
community involved in writing the open source program. Furthermore, PHP is a
platform independent server side scripting language so it can be run on all the major
operating systems. And with most of the web servers.
The pace of writing code in PHP is very fast because most of the code are available
online and freely downloadable. So there is no need to learn those concept of building
logics and it coding. The available scripts can easily be customized by any user who
will be having a little knowledge of programming. PHP allows you to separate HTML
code from scripted elements. These codes are self explanatory. The user can minimize
the development time by using PHP scripts.
Bioinformatics and Statistical Genomics L31
Well-maintained open source projects offer users additional benefits. You benefit
from an accessible and committed community who offer a wealth of experience in the
subject, as fast and as cheap as possible. Chances are that any problem you encounter
in your coding can be answered swiftly and easily with a little research.
Create a blank HTML file (use anything you want), rename it to "hello.php", open it
in a text editor and insert the following code in the body part of the HTML.
<?php
echo "Hello World!",
?>
It’s evident that whatever is between <?php and ?> are parsed to the server. To
view your page in the brwoser, copy hello.php in the appropriate directory
(DocumentRoot in httpd.conf), open your web browser and enter the URL
http://localhost/hello.php.
With just three lines of code, you can display a simple message on the screen. Lines
between <? Php and ?> tells the Web server that these lines lines of code have to be
executed by the PHP interpreter. Using <?php is the only possible way to tell the
Web server that PHP code has to be executed.
If PHP has been configured successfully and your Web server has been started, “Hello
World” will be displayed on the screen.
Your first version of "Hello World" produces just text. However, the main target of a
PHP program is to generate HTML code. In the next example, you will see a small
script generating the HTML version of "Hello World".
<html>
<head>
<title>Title of the site</title>
</head>
<body>
<?php echo 'Hello World<br>'; ?>
</body>
</html>
As you can see, the PHP code is included in the HTML code. <?php tells the server
that the PHP interpreter has to be started here. In the example you can see that this
parts of the document are static and other parts of the document are created
dynamically by PHP.
Another way to obtain the same target would be to generate the entire document
dynamically. This will be slower than the version you have just seen, but in some
cases it makes sense or is necessary to generate everything dynamically.
2
Introduction to PHP, Building Blocks and Flow control L31
1 <?php
2 echo '<html>
3 <head>
4 <title>Title of the site</title> '.
5 '</head>';
6 echo "<body>hello world<br></body></html>\n";
7 ?>
The first echo command consists of two parts. The first three lines can be found
between two single quotes. PHP recognizes that the command continues in the next
line and does not end in the first line of the echo command. This way multiple lines
can be treated as one command. Another way is to use a string operation as you can
see at the end of line number 4 of the echo command. After the single quote, we use a
point to tell PHP that the first string, which has just ended, has to be connected with
the next string. In this case the second string is </head> included in the single quote.
All components of the first echo command are passed to PHP in single quotes.
The second echo (line number 6) command contains the text we want to be displayed
on the screen. This time we pass the text to echo using double quotes. Using single
quotes or double quotes makes a significant difference: Single quotes are used to pass
static text to PHP. Using double quotes allows you to use variables within the string.
After the execution of the given script, the result will be a simple HTML document:
(Some dynamic variable can be added)
<html>
<head>
<title>Title of the site</title>
</head>
<body>hello world<br></body>
</html>
phpinfo() is a standard PHP function called phpinfo which tells the server to print out
a standard table of information giving you information on the setup of the server.
<?
phpinfo();
?>
Building Blocks
Variables
Just like programming languages, PHP allows us to define and declare variables. The
idea behind variables is to have a language component that can have different values
assigned to it. It is also possible to use variables as containers for storing data that is
used in many different places in your application.
<?php
3
Bioinformatics and Statistical Genomics L31
$text="hello world";
echo '<html><head><title>Title of the site</title></head><body>';
echo "$text<br>";
echo "$text<br>";
echo '</body></html>';
?>
Note: We have to use double quotes instead of single quotes; otherwise, the result
would be:
$text
$text
Like most other high-level languages, PHP works to a large extent without types and
tries to recognize the data type of a variable by itself. However, PHP provides a set of
different data types.
Variables are marked with $ in PHP. PHP marks all variables with a $ and does not
use @ and % as symbols while naming a variable.
In PHP, the variables names are case sensitive. Any variable is a combination of
alphabets, numbers and a underscore (_) character. The name of a variable may start
with a letter or an underscore. The number can not be a first character of any variable
name.The following example shows that $a is not equal to $A:
<?php
$a = "I am a string";
$A = "I am a string as well";
echo "a: $a; A: $A<br>\n";
?>
As you can see, in the result, the two strings are not the same.
4
Introduction to PHP, Building Blocks and Flow control L31
When a variable has to be processed by PHP, the interpreter follows some predefined
rules in order to recognize which data type a variable has:
If a sequence of characters starts and ends with quotes, it will be treated as a string:
$a = 'abc'
assigns the string abc to $a because the string is enclosed with quotes.
$a = 23
It means that 23 is assigned to $a. The value 23 is an integer value because there is no
point in it.
Comments in PHP
<?php
// this is a comment
/* a C-style comment */
echo 'hello world';
?>
In PHP comments can be added to the code as in C and C++. // tells the interpreter
that the entire line should not be executed. /* */ is the old C style, which is also
supported by PHP. C-style comments can be used to insert commands consisting of
multiple lines:
<?php
/*
a C-style comment
which is longer than just one line.
*/
?>
Control Statements
5
Bioinformatics and Statistical Genomics L31
Usually programs require control structures, which are used to decide at runtime what
a program has to do. PHP provides a broad range of methods.
IF statement
<?php
if (2 > 1)
{
echo '2 is higher than 1<br>';
}
?>
A message will be displayed on the screen because 2 is higher than 1. If the condition
weren’t fulfilled, nothing would be displayed.
If statements can also be used to find out whether a variable has already been defined.
<?php
if ($a)
{
echo '$a has already been defined';
}
else
{
echo '$a has not been defined yet';
}
?>
In this case the result will be “$a has not been defined yet” because $a has not been
used before or declared.
IF…ELSE
If a certain condition is fulfilled, PHP will execute the code in parentheses, but what
has to be done if a condition is not fulfilled? It is very often used in combination with
else. if any expression/condition returns false, the code of the else part will be
executed.
<?php
$a=23;
$b=34;
6
Introduction to PHP, Building Blocks and Flow control L31
Instead of using a second if statement in the else branch, it is also possible to use
elseif, which is in most cases the shorter and more elegant way.
<?php
$a=23;
$b=34;
Operators
== is used to check whether two variables are the same. =, however, is used to assign
on evalue or variable to the another variable.
<?php
$a=2;
if ($a == 2)
{
echo "$a is equal to 2";
}
?>
7
Bioinformatics and Statistical Genomics L31
Sometimes it is necessary to find out if two or more conditions are fulfilled. Therefore
multiple expressions can be combined using operators and parentheses.
<?php
$a=23;
You can use the && operator to tell PHP that both conditions have to be fulfilled. The
counterpart of && (and) is the || (or) operator. If || (or) is used, true will be returned if
at least one expression returns true.
<?php
$a=2;
<?php
$a=2;
SWITCH
To avoid long sequences of if statementsyou can use switch and case statements.
Switch and case are often used to find the right piece of code that has to be executed
from a list of possibilities.
<?php
$a=2;
switch ($a)
{
case 1:
echo "case 1: \$a is $a<br>";
break;
8
Introduction to PHP, Building Blocks and Flow control L31
case 2:
echo "case 2: \$a is $a<br>";
break;
case 3:
echo "case 3: \$a is $a<br>";
break;
}
?>
First, 2 is assigned to $a. The switch statement checks all cases and if the right value
is found, the branch is entered and PHP executes all the code until a break command
is found. If you execute the script, one line will be displayed:
case 2: $a is 2
In the next step you will try to use switch and case without using break as well:
<?php
$a=2;
switch ($a)
{
case 1:
echo "case 1: \$a is $a<br>";
case 2:
echo "case 2: \$a is $a<br>";
case 3:
echo "case 3: \$a is $a<br>";
}
?>
The result of the version using no break commands differs significantly, as you can
see in the following example:
case 2: $a is 2
case 3: $a is 2
All of a sudden two lines are returned and that is definitely not the result you want.
PHP searches for the right value and executes the code until a break command is
found. In your case no break commands are in the code, so it is executed until the end.
In some cases this might be the desired behavior of the program, but in most cases it
is not.
Another feature of switch and case is the ability to handle default values. If no value
in the list matches, PHP will execute the default branch. In the following example,
you are looking for 9, but 9 is not listed in the switch statement:
<?php
$a=9;
9
Bioinformatics and Statistical Genomics L31
switch ($a)
{
case 1:
echo "case 1: \$a is $a<br>";
break;
case 2:
echo "case 2: \$a is $a<br>";
break;
default:
echo "the value couldn't be found<br>";
}
?>
PHP will execute the default code because 9 has not been found in the list:
Array
An Array is a list of multi-valued variable. It stores one or more values, each one
identified by a number representing its position in the array.
The declaration of an array variable can be made by listing the elements that the array
would hold right at the time when you declare the array.
$varArray is the name we chose for the array variable, while element1, element2 ...
elementN are the values stored in the array in position 1, 2... N. The position will start
from 0 to N-1.
$varArray[0] = element1;
$varArray [1] = element2;
.
.
.
$varArray [N-1] = elementN;
Both the above methods perform the same assignment. The first one is more compact,
but in the second you need to know the values that you would enter in the array right
at the time when you initialize the array.
10
Introduction to PHP, Building Blocks and Flow control L31
Note : Remember that the first element of an Array is always identified by number
zero (0). This means that if an array holds eight elements, they will be numbered from
Array[0] to Array[7].
Adding elements to an array can be possible in PHP using the following syntax
$varArray[] = newvalue;
The above statement would append the value ' newvalue ' to a new element after the
existing last element in the array. Suppose the array had 5 values (arrayname[0] .....
arrayname[4]) and you had the above statement, the new value would be assigned to
6th element of that array (arrayname[5]).
Array data type could be useful during data processing operations. If we decide to
save variables in one array object it would be easier to manage them. This because it
is possible to process (read/write/edit) all of them by using a loop structure (for loop
or while loop). The loop's control variable would be used as the array's index.
<HTML>
<BODY>
<?
for ($k=0;$k<4;$k++)
echo ($vv[$k]);
for ($k=0;$k<5;$k++)
echo ("$vv[$k]");
?>
</BODY>
</HTML>
Associative Arrays
PHP allows to define a another kind of arrays called the associative arrays. An
associative array is an array in which the elements can be accessed through a keyword
instead of the index. Each element, in an associative array, is characterized by a
11
Bioinformatics and Statistical Genomics L31
keyword. This means that we will no more use indices to read/write/edit elements,
because they have been replaced by keywords. The associative arrays is constituted
by pairs such as "key - element".
$varArray = array (
"key1" => element1;
"key2" => element2;
...
"keyN" => elementN;
);
varArray is the name of the array variable , key1, key2..., keyN are the N keywords
through which we can access the respective elements - element1, element2, ...
elementN.
$person= array(
"name" => "XYZ",
"URL" => "http://www.xyz.com",
"email" => "[email protected]",
);
An associative array with three elements has been defined. The first element,
accessible through the keyword "name" is of string type and contains the value
"XYZ". The second element is a string too, it is accessible through keyword "URL"
and stores the value "http://www.xyz.com". Similar is the case with third and last
element.
Once we have defined such an array we could use the following script to display some
of the values
Sample Program
<?
echo ("Surf to the website $person[name] at $person[URL]!");
?>
Output :
count
To find out how many values are stored in an array count function is used. As soon as
you know the number of components of your array, it is an easy task to display the
content of the array on the screen:
<?php
$a = array("Wheat", "Rice", "Maize");
12
Introduction to PHP, Building Blocks and Flow control L31
$vals = count($a);
echo "Number of values in the array: $vals<br><br>\n";
The various cells of the array are accessed by using parentheses and the index of the
value:
<?php
$a = array("Wheat", "Rice", "Maize");
reset
The reset function set the pointer to the first element of an array.
sort
<?php
$a = array(23, 16, 8, 99);
sort($a);
arsort
13
Bioinformatics and Statistical Genomics L31
shuffle
next
You have seen how an array can be accessed by using an index or a foreach
command. Another way to process all values of an array is to use reset and next. Next
sets the pointer to the next value in the array and returns the current value. With the
help of a do/while loop, it is an easy task to go through the array:
<?php
$a = array(23, 16, 8, 99);
reset($a);
$val = $a[0];
do
{
echo "val: $val<br>\n";
}
while ($val = next($a));
?>
Loops
WHILE Loop
WHILE loopis used to execute a piece of code repleatedly depend on the given
condition/conditions.
<?php
echo '<html><body>';
$a=1;
DO..WHILE
14
Introduction to PHP, Building Blocks and Flow control L31
Sometimes it is necessary to execute the statements associated with the loop at least
once, Do-While loop can be used in this situaion.
<?php
echo '<html><body>';
$a=3;
do
{
$a=$a+1;
echo "a: $a<br>\n";
}
while ($a <= 5);
echo '</body></html>';
?>
Break
What can you do if you have to leave a loop in the middle of a block? Break is a
command that can be used to stop all kinds of loops in the middle of a block.
<?php
echo '<html><body>';
$a=1;
do
{
echo "a: $a<br>\n";
$a++;
if ($a == 3)
{
break;
}
}
while ($a <= 5);
echo '</body></html>';
?>
You want to execute the loop as long as $a is lower than 6, but if $a is equal to 3, you
want to exit the while loop.
If you execute the script, you can see the result in the browser:
a: 1
a: 2
15
Bioinformatics and Statistical Genomics L31
Two lines will be displayed because the loop is interrupted after printing two lines on
the screen.
Continue
Continue is used to stop the execution of a block without leaving the loop. The idea is
to ignore remaining steps in the loop.
<?php
echo '<html><body>';
$counter=0;
$test=10;
while ($counter < $test)
{
if ($counter %2)
{
$counter++;
continue;
}
echo "Current value of counter: $counter<br>";
$counter++;
}
echo '</body></html>';
?>
One line is generated for every second number the loop is processed for.
FOR
A for loop consists of a starting value, a condition that is checked every time the loop
is processed, and an expression that is executed after every time the loop is processed.
<?php
echo '<html><body>';
16
Introduction to PHP, Building Blocks and Flow control L31
echo '</body></html>';
?>
i: 0
i: 1
i: 2
i: 3
i: 4
17