Home > Whitepapers > PHP 4 for Beginners – a tutorial
Bookmark and Share

PHP 4 for Beginners – a tutorial

Posted on January 01, 2003 | Filed in Scripts

This tutorial may be reproduced without any modifications to this document for non-commercial, non-profit purposes. All other forms of usage requires the permission of the author – Ranjan Chari, email: [email protected]


PHP 4 for Beginners is a tutorial that was written initially to teach a few beginners the basics of PHP coding in classroom sessions. This tutorial is aimed at anyone who wants a fast start to programming in PHP 4. The intention here is to provide a comprehensive beginners tutorial that introduces the language and introduces the user to programming concepts thru PHP.


PHP is a successor of an older product called PHP/FI. This was a product created by Rasmus Lerdorf in 1995 and consisted of a bunch of Perl scripts for which kept track of user accesses to his resume. ‘PHP’ stood for ‘Personal Home Page and ‘FI’ stood for ‘Form Interpreter’. These scripts got a whole lot of attention from the programming communities and subsequently resulted in the birth/re-birth of PHP as we know it today. The name stands, now, for ‘Hypertext Pre-Processor’ which is a ‘GNUish’ derivative of the name.

PHP today runs on millions of websites and is a direct competitor to non-open source products such as ASP from Microsoft, ColdFusion from Macromedia etc. Now you may ask, ‘What’s the benefit of using PHP over ASP or ColdFusion ?’

There are many supporting answers, one of them being – “it makes sense to use a free product that offers all the functionality of paid products, greater platform support and which has support available all across the world.”

Some reasons are
1. PHP is free. It’s Open Source.
2. PHP runs on almost all operating systems and major hardware platforms.
3. PHP works with a large variety of webservers.
4. PHP works with more databases than any other product in it’s class.
5. PHP is easy.
6. The fact that it’s Open Source gives it the huge advantage of having a lot of free addons developed and released by the Open Source community. So a lot of addons for PHP are free where normally you would pay something for.
7. It’s easy to get PHP support virtually everywhere.
8. PHP works really great with MySQL which probably is the most popular database used on the web today.
9. There are lots of books on PHP as well as free online resources.
10. PHP is a true programming language and is very stable.
11. There are a large number of webhosts who provide PHP support on their hosting plans.

What does PHP do and how do I run it ?

PHP is an interpreted language which works in conjunction with a webserver. It allows static HTML pages to have ‘intelligence’. By this I mean that it will allow you do many more things than what you can accomplish via a simple HTML page. PHP is embedded into HTML. When a PHP page on a webservers is run, the webserver passes the PHP code to the PHP interpreter which in turn performs some actions, an example being communicating with a database or performing some calculation’ and passes the result back the webserver. The end result, i.e. the page displayed to the browser is plain old HTML.

In the case of Apache, PHP can be installed as an addon module. This means that Apache can be compiled for your system with PHP built into it. The clear advantage here is that if PHP is integrated into the webserver, you have a tightly integrated product that delivers superior performance as compared to a CGI model where information is exchanged between the webserver and a CGI module.

PHP works especially well under Linux/UNIX and with Apache. Windows support is present and is especially useful for development and testing purposes because most people do not have access to a Linux/Unix box and people seem to be most familiar with Windows based systems. My intention here is to tell you that for a live environment, it’s better to have a PHP driven website running on a Linux/Unix box with Apache rather than Windows and IIS. Of course this is only a comparative comment. PHP works fine under Windows. And you should work with whatever operating system you are comfortable with. Plenty of online tutorials are available for installations under various environments including the Mac.

PHP can be run Windows 95/98/2000/XP/NT/ME, Linux, FreeBSD, Unix/HP-UX,Mac OS X,OpenBSD, Solaris and other Unix variants.
PHP can work with a wide variety of servers namely: Apache, Caudium, IIS, PWS, iPlanet, Sambar, Xitami, fhttpd, Zeus, Oreilly Website Pro etc.

For this tutorial I am working with Apache and Windows XP and we will be using PHP as a CGI with MySQL support built-in.
That said, let’s get started with creating an environment where we can start learning PHP.

Installing PHP 4 and creating a development and testing environment

So what do we need to do:

Firstly download everything required. Download links: Apache 2.0.43-win32, PHP, MySQL.

Install and configure Apache. Test it.

Install and configure PHP. Test it.

Install and configure MySQL. Test it.

All of this is being done on a Windows XP system. These steps should work the same on Windows 2000 and ME. On Windows 9x and NT you’ll need a software package to be installed called InstMSI.exe. This package is available at microsoft.com. Windows 95 users require an update called the Windows 95 Socket 2 update which solves a number of Winsock2 and TCP/IP stack issues.

You can download the products by clicking the links provided above. Save everything in a directory that you can easily find later on. All of these products have several mirrors around the world. You may use any of them as long as you get a current product. If you get corrupted downloads from several locations then try disabling your download accelerator software if any is installed.

The product versions that we need are:

  • Apache_2.0.43-win32-x86-no_ssl.msi
  • php-4.2.3-installer.exe
  • mysql-3.23.53-win.zip

> INSTALL Apache

Now find and run the Apache installer.

1. “Welcome to the Installation Screen of Apache 2.0.43” Hit ‘Next’

2. Accept the terms. Hit ‘Next’

3. Read about the HTTP server. Hit ‘Next’

4. Server Information:

Network Domain: ‘xyz.com’ or simply ‘user’
Server Name: ‘localhost’
Administrator’s Email: ‘[email protected]

Leave the radio button on it default state for ‘all users’

Hit ‘Next’

5. Setup Type:

Typical Hit ‘Next’

Install the software.

Apache will successfully install and you should get a small Apache icon on the taskbar.

Open up a browser window and try this:



both are ‘loopback’ addresses and your browser will pull up the webpage hosted by the Apache webserver you just installed.

If you see the Apache test page you are fine. If not then check the install. Do you need to launch the service manually ?


Locate the installer file you downloaded for PHP and execute it.

1. Choose ‘Standard’ Installation. Hit ‘Next’

2. The default directory C:\PHP is fine. Hit ‘Next’

3. Mail Configuration: Your SMTP server is “localhost”, email is your email address. Hit ‘Next’

4. Server Type: Apache Hit ‘Next’

5. Now since we are using Apache we need to edit the httpd.conf file manually since this PHP installer does not does automatic configurations (yet) for Apache. So go to the program group created for Apache from your ‘Start’ menu and go to ‘Configure Apache Server’. There you’ll find a link to a text document called httpd.conf. Click it to open it in notepad.exe.

Search for something that looks like this:

# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"

Modify the DocumentRoot to be:

DocumentRoot "C:/www"

This directory will be the default place where all the pages are going to be served from. This is for convenience. Who likes to dig inside the Program Files directory area ?

So go ahead and create a directory called ‘www’ on your C: drive.

Search for something that looks like this:

# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.

and below that add the following lines so the text looks like this:

AddType application/x-tar .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .php4
AddType application/x-httpd-php .phtml
Action application/x-httpd-php "/php/php.exe"
ScriptAlias /php/ "c:/php/"
AddType image/x-icon .ico

All that you’re doing here is to tell the Apache webserver where to find the PHP interpreter and which filename extensions to associate with PHP.

Now locate text that looks like this:

# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses (

Listen 8080

Change the ‘Listen Parts’ to the IP addresses show above. This will ensure that your development server listens to Port 80. is a loopback IP address that will ensure that the browser tries to communicate with the Apache server on your system.

Save and close the file. Stop Apache and then start Apache.

Now using any text editor such as notepad create a test php file.

Insert the following code in the text document and save it as ‘test.php’ ( Remember that the extension should be .php)

<? phpinfo()?>

Now open up http://localhost/test.php in your browser. This php snippet will run and present you with PHP environment variables and other information. If this happens, you have successfully installed PHP and it’s talking nicely with your webserver.


Locate the MySQL zip and Unzip the file. Run Setup.exe from wherever you unzipped everything to. Let all the options be at default and keep hitting ‘Next’.

1. After the installation is completed. Go to C:\MySQL\bin and create a shortcut to WinMySQLAdmin

2. Execute WinMySQLAdmin

3. Create a Username and Password
Once you do this, the MySQL daemon will be accessible using this tool. Now the service mysqld-nt should have started. If not, start it using this tool.

4. Now open up the DOS (Command) prompt:

Type this: C:\cd mysql\bin
Hit ‘Enter’

Then type: C:\mysql\bin\mysql

Hit ‘Enter’

If you see something like …

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.23.53-max-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.


…your MySQL install was successfull.

(The test here is that the mysql monitor will not run without a MySQL daemon running on the system already.)

Okay, we’re done with the install. If you encounter problems at any stage check php.net, apache.org, mysql.com for new installation instructions, feedback and for installation instructions on other operating systems and webservers. Please note that the code you’re going to write, will work the same regardless of where you run them as long as PHP4 is installed.

Selecting a Text Editor

Now that we’re going to start actual coding you need to get hold of a decent text editor. By decent I mean a text editor that than provide you with multiple windows to look at two scripts simultaneously, syntax highlighting, line numbering, some text formatting functions, some search functions etc. I use TextPad as I am comfortable with it and have been using it for some time. UltraEdit, EditPlus, WinSyntax, DreamWeaver UltraDev/MX, Visual Studio are other alternatives in varying degrees of complexity and pricing. See what you have or what you like and go for something you’d want to use often. It pays to learn a smaller package better than a larger package ‘less better’. Of course your choices are also limited by your operating system. It may be true that you may just have to work with vi and pico on Linux. Anything that can write ASCII text will work fine for our purposes since code length is relatively small.

PHP Basics

> PHP Tags

PHP code is embedded in tags. These are special tags that let the webserver know which parts of an HTML page are PHP. Just like HTML tags we need to open and close tags.

PHP tags can be written as:

<? some code goes here ?>


<?php some code goes here ?>

The second variant is the more commonly used syntax and which will be used throughout this tutorial.

> echo and print

echo "Hello World";

Look at the syntax. Note the ‘ ” ‘ and the ‘ ; ‘. All textual information needs to go inside double inverted commas. All statements need to end with a ‘;’. The syntax will seem familiar to PERL programmers.

Save this file as echo.php and view it thru your browser by going to the loopback address. http://localhost/echo.php
You’ll see that ‘Hello World’ is printed out on the screen.

echo ("Hello World");

The example above does the exact same thing as the first example. You’re just using a syntax variant.


echo ("Hello World","Hello");

This will give you a parse error. But if you remove the parenthesis, it’s work fine. So it’s obvious that using the parenthesis limits you to a single ‘argument’.

If you look at the source of the page generated by either of these two examples, you’ll notice that there is no HTML. It’s just text that got printed out. This is because we’ve not specified that any HTML to be printed.

<TITLE>This is my Hello World Page</TITLE>
echo "Hello World<BR>\n";
print "Another Hello World 1<BR>";
print "Another Hello World 2<BR>";

So what does this example do ?

The output:

Hello World
Another Hello World 1
Another Hello World 2

The HTML source of the generated page:

<TITLE>This is my Hello World Page</TITLE>

Hello World<BR>
Another Hello World 1<BR>Another Hello World 2<BR>

By looking at the PHP code and the output we understand the following:
1. PHP can be stuck inside html using the opening and closing <?php tags.
2. the ‘print’ function is a lot like the ‘echo’ function.
3. Embedding HTML tags for formatting output is exactly the same as HTML. Ex:<BR>
4. The code generated can also be formatted using certain characters called escape characters. Ex: \n which is a carriage return.

echo (2+2);

This code above will output ‘4’.

echo (2+2).("Hello World"));

The code above will print out ‘4HelloWorld’

The parenthesis are required to separate the two logical entities. The period ‘.’ joins the sum of 2+2 and the string provided in the output. So essentially if you have two strings and you’d like to display them together in the output use a period.

You must note that the ‘print’ function can take only a single argument.

Variables & Syntax

A variable is a container. It contains some information that will be used in your program. Variables are case sensitive. Variables are declared with a ‘$’ sign. Look at the example below:

$mymismatch = 3+"hoopla";
print "$myname <BR>";
print "$Myname <BR>";
print "$mynumber <BR>";
print "$myaddition <BR>";
print "$mymismatch <BR>";

The output is:


As you can see $mymismatch does something different. It ignores the “hoopla” value. PHP is very easy with work with, with respect to variable assignments. You can assign any value to a variable at any time and interchangeably. This means that if you start of by declaring that a variable has numerical value and later assign a string value to it, it’s perfectly legal.

$var3=$var1 + $var2;
print "$var3 <BR>";
print "$var4 <BR>";
print "$var5 <BR>";
print "$var6 <BR>";

The Output:


Notice how the addition, multiplication, subtraction, modulus ‘operators’ are used. Whenever you need to perform a mathematical operation you need to use an ‘operator’.

//Some comments
#Some comments
/* My comments
on multiple lines */

The example above shows various methods to comment code in PHP. You have two options to write single line comments and one option to write multi-line comments. Commenting code is always a good idea, once code get’s complex, little notes always help the next time you get around looking at the code.

Variables can be accessed anytime and anyplace within your PHP code. So if a variable is declared once, it’s available to you always. The only time variables are not available ‘globally’ are when they are declared inside ‘functions’. More on ‘functions’ later.

Quotation Marks

PHP code uses single and double quotation marks in it’s coding syntax. When you use double quotes, the string enclosed within them is processed. Any variables inside that can be processed is processed and the actual or resultant value is substituted.

print "$var1"."$var2"."<br>";
print '$var1 $var2';


$var1 $var2

Note that with single quotes, stuff is printed the way it exists. With Double quotes variable substitution has been done do provide the final value. This process of substitution is called ‘variable interpolation’ in geekdom.

To put a single quote or a double quote within single or double quotes, just put in a backslash (/) right before it. Backslashes are called ‘escape’ characters.


An array is a variable that contains multiple values and where each value can be indexed individually.

$mycar=”Honda Accord”;

The example above is an array with one value. Now let’s say you wanted to store the names of multiple cars in the variable $mycar and wanted the ability to reference any variable individually.

$mycar[0] = "Honda Accord";
$mycar[1] = "Maserati";
$mycar[2] = "Honda Element";
$mycar[3] = "Toyota Celica";
print $mycar[0]." ".$mycar[1]." ".$mycar[2]." ".$mycar[3];


Honda Accord Maserati Honda Element Toyota Celica

Arrays can be used to store a bunch of related or un-related information that can be accessed using a ‘key’. A key can be an integer (numeral) or a string. The example above uses a numbers as keys. By calling a key you can extract the value of that key from the array.

Let’s look at some more examples to understand arrays clearly.

$mycar = array('Honda Accord', 'Maserati', 'Honda Element', 'Toyota Celica');
print $mycar[0]." ".$mycar[1]." ".$mycar[2]." ".$mycar[3];


Honda Accord Maserati Honda Element Toyota Celica

In the example above we have used a different style of defining an array. By default array keys are integers and begin with Zero.

$mycar = array('firstcar' => 'Honda Accord', 'secondcar' => 'Maserati', 'thirdcar' => 'Honda Element', 'fourthcar' => 'Toyota Celica');
print $mycar['firstcar']." ".$mycar['secondcar']." ".$mycar['thirdcar']." ".$mycar['fourthcar'];


Honda Accord Maserati Honda Element Toyota Celica

The example above uses strings as keys.

$mycar = array('firstcar' => 'Honda Accord', 'secondcar' => 'Maserati', 'thirdcar' => 'Honda Element', 'fourthcar' => 'Toyota Celica');
echo $mycar['thirdcar'];


Honda Element

You can access any value by calling the corresponding key in the array.

Now let’s assume you need to create an array that holds numerical as well as string values.

$myarray = array(‘myfirst’ =>’ One’, ‘mysecond’ =>2, ‘mythird’ => ‘Three’);

That is perfectly legal in PHP.

Here are some more examples illustrating some more functions relevant to arrays.

$myarray = array('myfirst' =>' One', 'mysecond' =>2, 'mythird' => 'Three');
$myarray['myfourth'] = '4';
### This sizeof() function will return 4 which is the size of the array.
echo sizeof($myarray)."<BR>";
### Takes an array as the argument and convert each key-value pair into a variable and value pair.
echo $myfirst."<BR>";

There are several more functions that deal with arrays, some have been listed below. For a complete list visit the php.net site.

$mostactive = array('MSFT','ORCL','IBM','DELL','INTC','NT');

// Does a string exist in an array ? True if it does, False if does not.
echo in_array('MSFT', $mostactive)."<BR>";

// Searches for a value in an array and return the position of the value if found.
echo array_search('INTC', $mostactive)."<BR>";

// Assigns the value of array elements to variables. In this case the first two values in the array

// are assigned to the two variables provided.
list ($a, $b) = $mostactive;
echo $a."<BR>";
echo $b."<BR>";

// Add a new value to the end of an array
array_push($mostactive, 'MMM');

echo $mostactive[6]."<BR>";

// Remove a value from the end of an array


// Remove a value from the top of an array


echo $mostactive[0]."<BR>";

// Add a value to the top of an array

echo $mostactive[0]."<BR>";




Lets take a look at a simple way to examine arrays.


$mostactive = array('MSFT','ORCL','IBM','DELL','INTC','NT');

//print_r( ) recursively prints out the key and values for an array




Array ( [0] => MSFT [1] => ORCL [2] => IBM [3] => DELL [4] => INTC [5] => NT )

Multi-Dimensional Arrays

Let’s say you have 3 friends. Each friend has a car and lives in a different city. Lets say you wanted to keep all this info in an array. You’d look at creating a multi-dimensional array. Accessing multi-dimensional arrays is very similar to single level arrays.


$mybuddies = array(

"names" => array('buddy1' => 'Larry',
'buddy2' => 'Curly',
'buddy3' => 'Moe'),

"cities" => array('city1' => 'New York',
'city2' => 'Chicago',
'city3' => 'Phoenix'),

"cars" => array('car1' => 'Dodge Viper',
'car2' => 'Honda Civic',
'car3' => 'Lincoln')

echo $mybuddies['names']['buddy1']."<br>";
echo $mybuddies['names']['buddy2']."<br>";
echo $mybuddies['cities']['city1']."<br>";
echo $mybuddies['cars']['car2']."<br>";



New York
Honda Civic

The array here is arranged for better readability. Essentially we are defining a whole bunch of arrays inside an array. When accessing a key we are specifying the container array, followed by the sub-level array followed by the key.

That’s all there is to it.

Control Statements

Control statements are statements inside a program that execute bits of code depending on conditions. Control statements are present in every programming language. Control statements in all programming languages work quite the same. Because logic is universally accepted to be similar.

For example you’d use an umbrella ‘if’ it were raining ‘or’ if it were really sunny and you wanted to protect your skin from sunburn.

Control statements allow you to program decisions into your code. Do something when something is true or false or equal to something or any kind of condition that you can construct.

There are many types of control statements. Each is ideal in a certain kind of scenario. Let’s examine these control statements and when to use them.

To create a program where decisions can be taken, we need to understand a few operators.

When we compare two values we use ‘comparison operators’.

Comparison Operators

= =    The Equal Operator: True if two values are equal to each other. Otherwise False
!=      Not Equal: True if two values are unequal. Otherwise False
<       Less than
>       Greater than
<=     Less than or equal to: True if the value on the left side is less than or equal to the value on the right. False otherwise
>=     Greater than or equal to: True if the value on the left is greater than or equal to the value on the right. Flase otherwise
= = = Identical: A new operator in PHP4 which is true if two values are equal and of the same type.

Logical Operators

and     Is true when both arguments are true
or        Is true when one argument is true
!          Is true if an argument following it (Example: $x !=1) is not true. False otherwise
xor      Is true if either but not both arguments are true.
&&      Same as ‘and’
||        Same as ‘or’


This type of conditional control statement executes block of code depending on whether a test condition is true or false.

In the example below $x is compared with $y. If $x is less than $y, a block of code is executed. If $y > $z a block of code is executed. If that fails, another block of code enclosed within an ‘else’ control statement is executed. An ‘if’ control statement can be executed without a corresponding ‘else’ statement. But an ‘else’ statement cannot exist on it’s own.


$x=1; $y=6; $z=8;

if ($x < $y)

echo ("X is less than Y <BR>");

if ($y > $z)

echo ("Y is greater than Z <BR>");

echo ("Y is less than Z");



X is less than Y
Y is less than Z

Now lets say you wanted to test for several conditions which are related, there is a variant of the If-else control statement.




if ($budget == 210000) {

print "You can buy a Bentley Arnage";}

elseif ($budget == 231000) {

print "You could buy a 2003 Aston Martin V12 Vanquish"; }

elseif ($budget == 80000) {

print "You could buy a Mercedes Benz S Class Sedan"; }

elseif ($budget == 37000) {

print "You could buy a Mercedes-Benz C320"; }

elseif ($budget < 30000) {

print "You could buy an Audi A4 1.8T"; }



You could buy an Audi A4 1.8T

Okay, so what have we done here ? We have successfully created a series of decisions based on certain conditional arguments. Note the we have used the ‘= =’ equivalence operator to check for equivalence comparison. If we had another ‘elseif’ statement after the last ‘elseif’ statement it would not be evaluated. Actually after any one condition is successfull, no other checks are performed.


The switch control statement allows conditional execution of code depending on the value of a single expression.





case 1:

print "The value is 1";

case 2:

print "The value is 2";

case 3:

print "The value is 3";

case 4:

print "The value is 4";

case 5:

print "The value is 5";

case 6:

print "The value is 6";


print "Nothing was found";



The value is 6

From the example above we notice that, the switch statement evaluates against a single expression. Unlike the ‘elseif’ statement, the switch statement will continue to evaluate subsequent expressions even if a true condition is found. A special statement called ‘break’ needs be used to prevent further examination of conditions once a match (true condition) is found. The ‘default’ statement is used to indicate an action that will be performed if everything else fails. The swtich statement is a clean way to test for multiple values of a single argument or expression.


Looping is a very powerful and commonly used programming technique. In theory there are two types of loops. ‘bounded’ and ‘unbounded’ loops.

A bounded loop will execute a certain number of times. An unbounded loop will execute till the time a certain condition become true or false.


The while loop checks a condition as a boolean and executes a statement. It keeps doing this again and again as longs as the condition is true.



while ($x<2003 && $x>2001)


print "the year of the Horse";



The Output here would ‘the year of the Horse’ repeated across the screen many times.

You can make all kinds of conditions for example: if $x !=0 or if !$x etc.


A close relative of the While loop, this kind of loop executes a statement atleast once, then checks a condition and if it’s still true executes the statement again.





print "The current value is $counter <BR>";

// Same as $counter=$counter+1; Other syntax variants $counter--
// The above are autoincrementers and autodecrementers.



while ($counter <=100)



The current value is 90
The current value is 91
The current value is 92
The current value is 93
The current value is 94
The current value is 95
The current value is 96
The current value is 97
The current value is 98
The current value is 99
The current value is 100

the FOR loop


for ($x=30; $x<=100; $x++)


print "The Value of x is $x <br>";



This is an example of an unbounded FOR loop. Essentially an unbounded loop is made into a bounded loop using conditions.

In the example above the for statement has 3 conditions. Each is separated by a semi-colon. The first is the initial expression. The second is the check condition. The third is the loop expression. The loop expression is executed at the end of every loop. The statements inside the ‘for’ loop get executed each time the loop does a loop. In the example above, leaving out the ‘{‘ and ‘}’ would work fine but it looks more organized this way.

Nested Loops

Loops can be placed inside loops for interesting results. An example to illustrate a scenario where you’d need to do this.

Lets say we need to print the multiplication tables for 5 to 10 and upto 12 multiplication values. We can do this using loops.


for ($x=5; $x<11; $x++)


for ($y=1; $y<13; $y++)


print "$x multiplied by $y"." = ".($x * $y)."<BR>";


print "<BR>";




5 multiplied by 1 = 5
5 multiplied by 2 = 10
5 multiplied by 3 = 15
5 multiplied by 4 = 20
5 multiplied by 5 = 25
5 multiplied by 6 = 30
5 multiplied by 7 = 35
5 multiplied by 8 = 40
5 multiplied by 9 = 45
5 multiplied by 10 = 50
5 multiplied by 11 = 55
5 multiplied by 12 = 60


10 multiplied by 1 = 10
10 multiplied by 2 = 20
10 multiplied by 3 = 30
10 multiplied by 4 = 40
10 multiplied by 5 = 50
10 multiplied by 6 = 60
10 multiplied by 7 = 70
10 multiplied by 8 = 80
10 multiplied by 9 = 90
10 multiplied by 10 = 100
10 multiplied by 11 = 110
10 multiplied by 12 = 120

The example above iterates from 1 to 12 for each multiplication table value between 1 to 10. Is’nt this cool!

Loop and Control Statement Terminators

Often you might want to exit out of a loop. PHP has two constructs to do just this. exit( ) and die ( ).


for ($x=5; $x<11; $x++)


for ($y=1; $y<13; $y++)


print "$x multiplied by $y"." = ".($x * $y)."<BR>";


die("This is getting boring");




5 multiplied by 1 = 5
5 multiplied by 2 = 10
5 multiplied by 3 = 15
5 multiplied by 4 = 20
5 multiplied by 5 = 25
5 multiplied by 6 = 30
5 multiplied by 7 = 35
5 multiplied by 8 = 40
5 multiplied by 9 = 45
5 multiplied by 10 = 50
5 multiplied by 11 = 55
5 multiplied by 12 = 60
This is getting boring

die( ) is useful when you want to stop execution of a loop for any reason and exit with an informative message. Using exit( ) in this example will do exactly the same thing but exit is useful when you want to get out of a script right then and there. die( ) on the other hand is useful to test for a certain condition and if it’s true exit the whole program with a useful message.


Functions are pieces of code that you can re-use. All that you need to know is what kind of input it requires and you get the desired output.

For example echo( ) is a function. So is die( ) and every other command we have used till now. These are functions that have programmed by the PHP developers. But we can create our own functions. Functions help in providing us with the ability for procedural abstraction. Essentially it means that you can create blocks of code which can be reused for different tasks. For example if you knew that you’d need to use a lot of actuarial (insurance) formulae in your programs, you could create a set of functions that would let you perform these formulae without re-writing them for each program.


function tolkien()

print "Lord of the Rings <BR>";




Lord of the Rings


function totalincome($mysalary, $mydividend, $myinterest)

print "My total income is:".($mysalary + $mydividend + $myinterest);

totalincome(60000, 1000, 200);



My total income is:61200

In these two examples we see that functions can work with or without arguments passed on to them. Functions can be useful in large programs with repetitive tasks. Remember variables declared inside a function are not available outside a function.


totalincome(60000, 1000, 200);

print $adder;

function totalincome($mysalary, $mydividend, $myinterest)

global $adder;
$adder = $mysalary + $mydividend + $myinterest;




The example above illustrates that you can place functions any where in the program. PHP4 actually pre-compiles the program to see where functions occur. This used to be different in PHP3. The ‘global’ declaration makes the variable scope ‘global’.

You can store functions in include files. These are files that can be called from within a php program (script) and would be then considered to be part of the program. This is useful when you need to use the same functions over multiple pages.

The syntax is:


include "my_functions.inc";


Let’s look at some more function examples. Till now we have seen that functions can be passed some arguments which are acted upon. Now lets see how to pass some information between functions.

The code below illustrates the use of the command ‘return’. return sends back the resulting value of the statements that were executed within the function. In the example below, a function addme( ) has been created which adds two numbers. The second function multme( ) multiplies two numbers. The resulting value ($val) is returned and the value is assigned to $mysum. $mysum is used in turn in multme( ). The resulting value is again passed back and assigned to $mymult.


function addme($x, $y)

$val = $x + $y;
return $val;

function multme($x, $y)

$val = $x * $y;
return $val;

$mysum = addme(10, 15);

$mymult = multme($mysum, 20);






function cities($a="phoenix", $b="seattle", $c="san francisco")


echo "$a <br>";
echo "$b <br>";
echo "$c <br>";





san francisco

The above example shows a variant of assigning argument values inside a function.

Strings and Regular Expressions

It’s obvious that strings are going to be used in almost all programs. It become imperative to know ways to do things with strings, to search for patterns. How do you count the number of characters in a string ? Does a string contain a vowel ? We’ll to do stuff like this, we have some really handy built-in PHP functions and certain methods for searching and sifting through strings called Regular Expressions. PERL users would realize how useful PERL’s powerful regular expression capabilities are – we’ll PHP is quite strong with string manipulation too.


$mytext = "I think 640k should be more than enough for anyone";

print "$mytext <BR>";

print strtolower($mytext)."<BR>";

print strtoupper($mytext)."<BR>";

print ucfirst(strtolower($mytext))."<BR>";

print ucwords($mytext)."<BR>";



I think 640k should be more than enough for anyone
i think 640k should be more than enough for anyone
I think 640k should be more than enough for anyone
I Think 640k Should Be More Than Enough For Anyone

strtolower( ) : Converts a string to lower case
strtoupper( ): Converts a string to upper case
ucfirst( ): Converts the first character to upper case
ucwords( ): Converts the first character of each word to upper case

Let’s look at some more string functions.


$mytext = "My broker told me that ING is a good investment";
$moretext = 'His actual words were "Buy it for the long term"';

// addslashes( ) adds backslashes where necessary.

print addslashes($moretext)."<BR>";

// stripslashes( ) strips the backslashes addres before special characters.

print stripslashes(addslashes($moretext))."<BR>";

// explode( ) take a string separator, in this case it's a space, a string and
// breaks it up into chunks and stores it in an array

$myarray=explode(" ", $mytext);

// The while loop here uses the each( ) function to loops that many times as there
// are elements in the array.

while ($myvar= each($myarray)) {

echo $myvar["key"];
echo " - ";
echo $myvar["value"];
echo "<BR>";


echo "<BR>";

//implode( ) is the opposite of explode( )

$myoriginaltext = implode(" ", $myarray);

print "$myoriginaltext <BR>";

//strlen( ) counts the number of character in a string including whitespaces

$mystringlength = strlen($myoriginaltext);

print "The number of characters in the string is: $mystringlength <BR>";



His actual words were \”Buy it for the long term\”
His actual words were “Buy it for the long term”
0 – My
1 – broker
2 – told
3 – me
4 – that
5 – ING
6 – is
7 – a
8 – good
9 – investment

My broker told me that ING is a good investment
The number of characters in the string is: 47

Another example:


$mytext="The quick brown fox jumped over the lazy dog";

// 3 arguments are provided.
// The string, the start position which starts always at '0', the end position including whitespaces.

print substr($mytext, 0, 5)."<BR>";

// Here the start position is 5, the negative (-4) specifies the end position counting backwards from
// the end of the string

print substr($mytext, 5, -4)."<BR>";

// In the example below, the start point is only specified. The end point by default is the end of the
// string

print substr($mytext, 2)."<BR>";



The q
uick brown fox jumped over the lazy
e quick brown fox jumped over the lazy dog

Regular Expressions

Well we looked at some string functions. Now let’s take a look at regular expressions. PHP provides two styles of regular expression syntax. Posix and PERL. Posix is the default syntax. If you’d like to use PERL syntax for regular expressions you need to compile in the PERL compatible regular expression library. We’ll stick with Posix.

Regular expressions are ways in which patterns within text can be described.

Let’s see a few examples with ereg( ) which is the most common regular expression function.


$mytext="The quick brown fox jumped over the lazy dog who has been eating too much";
// '^' matches text at the beginning of a string.
// The syntax below first specifies the expression to be matched and then the string

$bool=ereg("^The", $mytext);

// In this instance $bool has a match. So it's content will be = 1;

print $bool."<BR>";

// '$' matches a sub-string at the end of a string. The example below again would be true.

$bool=ereg("much$", "$mytext");

print $bool."<BR>";


Let’s explore regular expressions deeper.

^mystring – will match a string beginning with ‘mystring’. So ‘mystring is a long string’ will match. But ‘ I have a long string called mystring’ will not match.

mystring$ – will match any string ending with ‘mystring’. ‘This is mystring’ will be a match.


We have 3 wildcard modifiers that can add greater flexibility to our regular expression search.

* :Match zero or more instances

+ :Match one or more instances

? :Match only zero or one instance

‘am+’ will match ‘am i alive ?’, ‘amadeus’ etc.

‘micros?’ will match ‘micro’, ‘microsoft’. The ‘?’ modifier excluded the preceeding character from it’s match.

‘ar*’ will match ‘argentina’, ‘arable’, ‘arabia’ etc.


Lets say we wanted to match ‘mxxx’ within a string. Should we write ‘mxxx*’ ?. What if we needed the character ‘m’ followed by exactly 3 ‘xxx’.

mx{3} : match the character ‘m’ followed by exactly 3 ‘x’s.

mx{1,3} : match the character ‘m’ followed by a minimum of 1 ‘m’ and a maximum of 3 ‘x’s.

mx{2,}: match the character ‘m’ followed by atleast 2 ‘x’s.

mx.x : The period here is a wildcard. This will match ‘mxyx’, ‘mxtx’ etc.

r(an)+ : match the character ‘r’ followed by ‘a’ and ‘n’. The parenthesis indicates a sequence of characters that need to be evaluated together. So ‘random’, ‘randomize’, ‘ranaway’ will all match.

^me | ^you : match any string beginning with ‘me’ OR ‘you. The pipe here represents an ‘OR’ operator.

Character Ranges

[xyz] : match a string containing x, y or z.

[a-z] : match a single lower case letter from ‘a’ to ‘z’

[a-zA-Z] : match a single lower case letter or upper case letter from ‘a’ to ‘z’ or ‘A’ to ‘Z’

[1-4] : match a single digit from 1 to 4

[a-zA-Z0-9] : match any alphanumeric character

[^1-4] : match anything but characters 1,2,3,4. : A carat within a square bracket negates the matching criteria. (Read as ‘don’t match’)

A useful function for looking through strings and replacing a part of it is: ereg_replace( )

The syntax is: ereg_replace(pattern, replacement, string)

And here’s an example:


$mystring = "With great power, comes great responsibility";

print "The original string is: \"".$mystring."\""."<BR>";

$modistring = ereg_replace("great","awesome",$mystring);

print "The modified string is: \"".$modistring."\""."<BR>";



The original string is: “With great power, comes great responsibility”
The modified string is: “With awesome power, comes awesome responsibility”

Date and Time functions

Time and Date in PHP are dependent on the timestamp which is the number of seconds between January 1, 1970 and the current date and time. January 1970 has something to do with the invention of Unix and this time is also called the Unix Epoch time or Time 0.

This timestamp can be obtained by using the time( ) function. It will return the number of seconds elapsed since January 1, 1970. From this integer we can figure out a everything related to date and time.

echo time( );

Let’s look at another function getdate( );


print_r (getdate());


Array ( [seconds] => 38 [minutes] => 45 [hours] => 23 [mday] => 6 [wday] => 5 [mon] => 12 [year] => 2002 [yday] => 339 [weekday] => Friday [month] => December [0] => 1039236338 )

getdate( ) can be passed a time stamp for conversion into an array similiar to the one above.

We can also reverse the process and create a timestamp out of a set of time and date values.

// create a timestamp for 11:15:10 December 7, 2002 using the mktime( ) function.
echo mktime(11, 15, 10, 12, 7, 2002);



File System

The following example illustrates how you can use PHP to access your file system. PHP can perform several useful file system related operations.


// set the directory I'd like to explore

// This is my directory.

$path = "/WWW";

// opendir() returns a directory handle used in closedir(), readdir(), and rewinddir() function calls.

// readdir() reads an open directory handle

while ($myfile = readdir($mydir)) {
print $myfile."<BR>";

// This example will work fine without closing the directory handle.



Let’s look at another example where we create a subdirectory using PHP.


// See how simple it is to use PHP to create directories. Here you've create a directory called
// 'phprules' and given it the permission 0777.

$mynewfolder = "phprules";
mkdir($mynewfolder, 0777);


Let’s look at an example with a Date/Time function alongs with a File System Function. Let’s say you wanted to know when the last time a particular file was accessed.


// First you specify a file for which the last access time needs to be procured.


print "The file $myfile was last accessed at: " . date( "D m/d/Y h:i:s a", fileatime("$myfile"))."<BR>";

print "The file $myfile was last modified at: " . date( "D m/d/Y h:i:s a", filemtime("$myfile"))."<BR>";



The file test1.php was last accessed at: Sun 12/08/2002 12:11:07 am
The file test1.php was last modified at: Sun 12/08/2002 12:11:07 am

© 2003 Ranjan Chari