Anu Sharma: Introduction To PHP, Building Blocks and Flow Control

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

L31

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.

It is a server-side scripting language usually written in an HTML context. Unlike an


ordinary HTML page, a PHP script is not sent directly to a client by the server;
instead, it is parsed by the PHP binary or module, which is server-side installed.
HTML elements in the script are left alone, but PHP code is interpreted and executed.
PHP scripts can query databases, read and write files, communicate with remote
servers - the possibilities are endless. The output from PHP code is combined with the
HTML and the result sent to the user’s web-browser, therefore it can never tell the
user weather the web-server uses PHP or not, because all the browser display is
simple HTML code.

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.

Reasons for using PHP

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.

Working with PHP

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.

PHP follows C language syntax. The statements will be terminated by a ;.

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>

Shortest script in PHP

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

Data Types and Functions

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.

Data Types in PHP

Data Type Description


Int, integer Numeric values
Double, real Floating-point values
String A sequence of characters
Array A pool of values
Object An artificial, user-defined data type

Variables and Names

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.

a: I am a string; A: I am a string as well

4
Introduction to PHP, Building Blocks and Flow control L31

Automatic Data Type Recognition

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.

If a number does not contain a point, it is treated as an integer value:

$a = 23

It means that 23 is assigned to $a. The value 23 is an integer value because there is no
point in it.

If a number contains a point, it will be treated as a floating-point number:

$a = 3.14159 makes PHP assign a floating-point value to $a.

Comments in PHP

Documentation is nearly as important as the code of a program. To reduce the costs of


maintaining a product and to reduce the time required to become familiar with the
source code, it is essential to add suitable comments to your programs. PHP provides
some simple ways to add comments to a program:

<?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

if is used to check whether a certain expression or condition is true or not.

<?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;

if ($a > $b)


{
echo 'a is higher than b';
}
else
{

6
Introduction to PHP, Building Blocks and Flow control L31

echo 'b is higher than a';


}
?>

IF…..ELSEIF (elseif ladder) Statements

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;

if ($a > $b)


{
echo 'a is higher than b';
}
elseif ($b > 30)
{
echo 'b is higher than a and higher than 30.';
}
?>

Operators

S. No. Symbol Description


1. == is equal
2. > Is greater than
3. < Is less than
4. >= Is greater or equal
5. <= Is less than or equal
6. != Is not equal
7. && and (to connect two or more conditions)
8. || or (to connect two or more conditions)
9. ! not (negation)

==, && and || 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;

if ($a > 10 && $a < 50)


{
echo "$a higher than 10 and lower than 50";
}
?>

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;

if ($a > 10 || $a < 50)


{
echo "$a higher than 10 or lower than 50";
}
?>

You can combine more than one operator in a condition.

<?php
$a=2;

if (($a > 10 && $a < 20) || $a == 2)


{
echo "$a higher than 10 but lower than 20 or exactly 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:

the value couldn't be found

Array and Loops

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.

Array Declaration Methods

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 = array (element1, element2, ..., elementN);

$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.

There is another way to declare an array variable. It is possible to assign a value to


each position of the array through the following syntax

$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

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]).

Example of using Arrays

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>
<?

$vv = array ("<BR>","Everything ", "can ", "wait" );

for ($k=0;$k<4;$k++)
echo ($vv[$k]);

$vv[]= ", not agriculture";

for ($k=0;$k<5;$k++)
echo ("$vv[$k]");

?>
</BODY>
</HTML>

The script above would generate an HTML page as follows

Everything can wait


Everything can wait, not agriculture

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.

Look at the following example where associative arrays are used

$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 :

Surf to the website XYZ at http://www.xyz.com

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";

for ($i = 0; $i < $vals; $i++)


{
echo "Value number $i: $a[$i]<br>";
}
?>

The various cells of the array are accessed by using parentheses and the index of the
value:

Number of values in the array: 3

Value number 0: Wheat


Value number 1: Rice
Value number 2: Maize

Displaying all records on the screen can also be done differently:

<?php
$a = array("Wheat", "Rice", "Maize");

foreach ($a as $x)


{
echo "$x<br>";
}
?>

reset

The reset function set the pointer to the first element of an array.

sort

sort function arrange the value in ascending order.

<?php
$a = array(23, 16, 8, 99);
sort($a);

foreach ($a as $val)


{
echo "val: $val<br>\n";
}
?>

arsort

13
Bioinformatics and Statistical Genomics L31

To sort data in a reverse order, use arsort instead of sort.

shuffle

shuffle—a function for putting values in random order in the array.

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;

while ($a <= 5)


{
echo "a: $a<br>\n";
$a=$a+1;
}
echo '</body></html>';
?>

The numbers from one to five are displayed.

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>';
?>

The output of the script is:

Current value of counter: 0


Current value of counter: 2
Current value of counter: 4
Current value of counter: 6
Current value of counter: 8

One line is generated for every second number the loop is processed for.

FOR

If a block has to be executed a fixed number of times, it is recommended to use for


loops instead of while loops.

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>';

for($i = 0; $i < 5; $i=$i+1)


{

16
Introduction to PHP, Building Blocks and Flow control L31

echo "i: $i<br>\n";


}

echo '</body></html>';
?>

The output of the script is:

i: 0
i: 1
i: 2
i: 3
i: 4

17

You might also like