Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

Hypertext Pre-processor: What is PHP?

What is PHP?
Hypertext Pre-processor (PHPs) is a server-side scripting language, and server-sidescripts are special
commands you must place in Web pages. Those commands are processed before the pages are sent from
your Server to the Web browser of your visitor. A typical PHP files will content commads to be executed
in the server in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags.

When you type a URL in the Address box or click a link on a Web page, you're asking a Web server on a
computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If
that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did
before the Web server sent it. After receiving the file, your Web browser displays its contents as a
combination of text, images, and sounds. In the case of an PHP page, the process is similar, except there's
an extra processing step that takes place just before the Web server sends the file. Before the Web server
sends the PHP file to the Web browser, it runs all server-side scripts contained in the page. Some of these
scripts display the current date, time, and other information. Others process information the user has just
typed into a form, such as a page in the Web site's guestbook
To distinguish them from normal HTML pages, PHP files are usually given the ".php" extension.

What Can You Do with PHP?


There are many things you can do with PHP.
• You can display date, time, and other information in different ways.
• You can make a survey form and ask people who visit your site to fill it out, send emails, save the
information to a file, etc

What Do PHP pages Look Like?


The appearance of an PHP page depends on who or what is viewing it. To the Web browser that receives
it, an Active Server Page looks just like a normal HTML page. If a visitor to your Web site views the
source code of an PHP page, that's what they see: a normal HTML page. However, the file located in the
server looks very different. In addition to text and HTML tags, you also see server-side scripts. This is
what the PHP page looks like to the Web server before it is processed and sent in response to a request.

What Do PHP pages Look Like?


Server-side scripts look a lot like HTML tags. However, instead of starting and ending with lesser-than ( <
) and greater-than ( > ) brackets, they typically start with <?php or <? and will typically end with ?>. The
<?php or <? are called anopening tags, and the ?> is called a closing tag. In between these tags are the
server-side scripts. You can insert server-side scripts anywhere in your Web page--even inside HTML tags.

Do You Have to Be a Programmer to Understand Server-Side Scripting?


There's a lot you can do with server-side scripts without learning how to program. For this reason, much
of the online Help for PHP is written for people who are familiar with HTML but aren't computer
programmers.

1
Creating my first PHP file

In this page we will add PHP scripting languaje codes to our regular HTML page, we will learn how to
write texts and how to concatenete them and write some special characters, and we will start using
variables.

In our fisrt step to learn PHP scripting languaje we will modify a regular HTML page and we will add to it
PHP commads. Bellow we will find a regular HTML page:

mypage.html

<html>
<head>
<title>This is my page</title>
</head>

<body>
This is the content of my page.

</body>

</html>
To create a PHP page using the page above as our model, the first important action is to rename our file. In
our case we will name the file "mypage.php". When a file with ".php" extension is placed in the server
and the corresponding url is visited, the server will process the file before sending it to the client, so that
all PHP commands will be processed. We may just change the name of our file as propoused and save it
to our server (without any additional changes), and when visiting the corresponding URL the result will be
exactly the same (because there is nothing to be processed in the page) .

To this renamed page ("mypage.php") we will add a small PHP command within <?php opening tag and
?> closing tag.

mypage.php

<html>
<head>
<title>This is my page</title>
</head>

<body>
This is the content of my page.
<?php
print "Do you like it?";
?>

</body>
</html>

2
When visiting the page, the server will process the page to execute all PHP commands in the page, which
will be located within <?php opening tag and ?> closing tags. In our case "print" command will write
to the resulting page the text contained between brakets ("Do you like it?"). Often, instead of print
command, echo command is used to output string. At the end of the line we will add ";" (otherway we
will get an error). We may use "echo" command instead of "print", and the result will be identical.

We may also include all the php commands in one line by placing the code bellow in our page.

<?php print "Do you like it?"; ?>

Between opening and closing tags we may include several lines with executable commands as shown
bellow (we must write ";" at the end of each line):

mypage.php

<html>
<head>
<title>This is my page</title>
</head>

<body>
This is the content of my page.
<?php
print "Do you like it?";
print "<br>";
print "<b>If not, please visit a different page.</b>";
print "<br>";
print "<h1>Goodbay</h1>";
?>

</body>
</html>

Additionaly we may add several opening and closing tags within our page with executable commands.

3
mypage.php

<html>
<head>
<title>This is my page</title>
</head>

<body <?php print "bgcolor=#FFFFFF"; ?>>


<?php
print "Hello!<br>";
?>
This is the content of my page.
<?php
print "Do you like it?";
print "<br>";
print "<b>If not, please visit a different page.</b>";
print "<br>";
print "<h1>Goodbay</h1>";
?>

</body>

</html>
As sown in the example above we may add PHP scripts within HTML tags.

Concatenation of strings
Check the codes bellow:
Code 1

<?php
print "Hello!<br>";
print "I am Joe";
?>

Code 2

<?php
print "Hello!<br>"."I am Joe";
?>

The pages containing any of the codes above will be exactly the same. We have just put both lines in one,
and to do that we have use a point between the two texts we want to show in our pages. The point used in
Code 2 will concatenated both strings.

4
Writing some special characters
Check the codes bellow:
The Code The output
Use "\n" to add a line break Use "\n" to add a line break
AA
<pre> BB
<?php CC
print "AA\nBB\nCC\nDD\nEE"; DD
?> EE
</pre>
Use "\"" to add brakets<br> Use "\"" to add brakets
<?php He said "Hello" to John
print "He said \"Hello\" to John";
?>

Using variables: first step


With PHP we may also use variables. The variables used in PHP will always start with "$", as for example
$i, $a, $mydata, $my_name etc. There are some words which we are not allow to use as a name for a
variable, but as we probably do not know which ones are they, our best decission will be to use very
descriptive variable names:
$my_favorite_song
$my_counter
$username
etc
In the example bellow we have write a PHP page using some variables:

mypage.php

<?php
$my_name="Joe";
$my_hello_text="Hello everybody!";
$year_create=2002;
?>
<html>
<head>
<title>This is <?php print $my_name; ?>´spage</title>
</head><body>
<?php print $my_hello_text; ?>

This page was written in <?php print $year_create; ?>.


</body></html>

5
In this example, we have defined three variables (line 2, 3 and 4) and we have included the information in
the variable latter within the HTML code.

Check those variables carefully: $my_name, $my_hello_text and $year_create has not been defined in
advance (we have add a value to the variables the first time they have used them in the file, without
letting know the program we will used it in advance), and the values do not contain the same kind of
content:

$my_name, $my_hello_text are strings


$year_create is a number

We may also use variables in the following ways:

The Code The output


<?php This page was written in 2002
$year_create=2002;
print "This page was written in
".$year_create;
?>
<?php This page was written in 2002
$year_create=2002;
print "This page was written in
$year_create";
?>
<?php This page was written in 2002
$the_text="This page was written in
";
$year_create=2002;
print $the_text.$year_create;
?>
<?php This page was written in 2002
$the_text="This page was written in
";
$year_create=2002;
print "$the_text$year_create";
?>

6
PHP tutorial: Displaying Date and Time

Displaying Date and Time

The date and time we will show how to display in this tutorial is the one specified by the server which is
hosting our pages. In case you want to display a different date or time (p. e., your clients are mostly from
Belgium but your server is located in US and you want to display the local time in Belgium) you will find
how to do it latter on this page.

In the table bellow we have include the PHP code necessary to display one by one all the time and date
related information. By copying the code in the first column to your page you will get the data which is
explained in the third column. The column in the middle is the value of those data the day we were
preparing this page.
Code Output
<?php print date("a"); ?> pm "am" or "pm"
<?php print date("A"); ?> PM "AM" or "PM"
<?php print date("d"); ?> 15 Day of the month: 01 to 31
<?php print date("D"); ?> Tue Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat
<?php print date("F"); ?> OctoberMonth: January, February, March...
<?php print date("h"); ?> 03 Hour: 01 to 12
<?php print date("H"); ?> 15 Hour: 00 to 23
<?php print date("g"); ?> 3 Hour: 1 to 12
<?php print date("G"); ?> 15 Hour: 0 to 23
<?php print date("i"); ?> 26 Minutes: 00 to 59
<?php print date("j"); ?> 15 Day of the month: 1 to 31
<?php print date("l"); ?> TuesdayDay of the week: Sunday, Monday, Tuesday...
<?php print date("L"); ?> 0 Is it a leap year? 1 (yes) or 0 (no)
<?php print date("m"); ?> 10 Month: 01 to 12
<?php print date("n"); ?> 10 Month: 1 to 12
<?php print date("M"); ?> Oct Month: Jan, Feb, Mar, Apr, May...
<?php print date("s"); ?> 03 Seconds: 00 to 59
Ordinal: 1st, 2st, 3st, 4st... Need to be used with a numeric
<?php print date("S"); ?> th
time/date value. See latter.
<?php print date("t"); ?> 31 Number of days in the month: 28 to 31
<?php print date("U"); ?> 1034691963 Seconds since 1970/01/01 00:00:00
<?php print date("w"); ?> 2 Day of the week: 0 (Sunday) to 6 (Saturday)
<?php print date("Y"); ?> 2002 Year (four digits)
<?php print date("y"); ?> 02 Year (two digits)
<?php print date("z"); ?> 287 Day of the year: 0 to 365
<?php print date("Z"); ?> -21600 Difference in seconds from Greenwhich meridian

7
As shown in the table the commands we are using in all case are "print" (in order to show the values to the
visitor) and "date" (which will allow us to get the data corresponding to the string code we are using
between brakets).
So we already know how to obtain the data and how to show it in our page, but if we want to display
different values simultaneously, we have at least three option:

The Code The output


<?php print date("Y"); ?>:<?php print date("m"); ?>: <?php print date("d"); ?> 2002:10:15
<?php print date("Y").":".date("m").":".date("d"); ?> 2002:10:15
<?php print date("Y:m:d"); ?> 2002:10:15

The first option is very easy to understand (we have just copied the code from the table one by one). The
second option concatenates the data basically in the same way, and the third one is probably the most
useful system, but the one we must understand before using it.

Command "date" will get the data we want to display, and that data is specified by the string used within
data (in our case: "Y:m:d"). Each character in this string may or may not have a meaning depending upon
there is or there is not a value asociate with that letter (see the first table in this page). In our case some
characters will be replaced by its corresponding value:
Y - Year (four digits)
. no meaning
m - Month 1 to 12
. no meaning
D - day of month 1 to 31

Check this usefull examples:

The Code The output


<?php print date("Y:m:d H:i") ?> 2002:10:15 15:26
<?php print date("l dS of F Y h:i:s A"); ?> Tuesday 15th of October
2002 15:26:03 PM
The time is <?php print date("H:i") ?>. The time is 15:26. That
That means it's <?php print date("i") ?> means it's 26 minutes past 15
minutes past <?php print date("H") ?> o'clock. o'clock.

Take care when using date command or you may get unwanted data as shown in the first row in the table
bellow (use the code in second row instead):
The Code The output Character with meaning
<?php print date("Today is l"); ?> WETo15pm02 2603 The following characters have a meaning:
Tuesday T, d, a, y, i, s, l
<?php print "Today is ".date("l"); ?> Today is Tuesday Only data asociated to "l" (day of the
week) is requested

8
Example: Link of the Day

What if you wanted to have a link that points to a different page every day of the week? Here's how you
can do that. First, create one page for each day of the week and name them "Sunday.htm," "Monday.htm,"
and so on.

To make the link, copy the code bellow to your page

<a href= <?php print date("l"); ?>.htm>Link of the Day</a>


Place the code in your ".php" page where you want it to appear. When you click this link in your browser,
it will take you to the "Link of the Day".

Using "S" with date comand.


Lets suppose we are using the code bellow in different consecutive days:
Day Code Output
2002/01/01 <? php print date("nS of F"); ?> 1st of January
2002/01/02 <? php print date("nS of F"); ?> 2nd of January
2002/01/03 <? php print date("nS of F"); ?> 3rd of January
2002/01/04 <? php print date("nS of F"); ?> 4th of January
The "S" character included within command date will allow us to show "st", "nd", "rd" or "th" values
depending on the number preceding the character "S".

Displaying local time


In this tutorial we will consider our server is located in a different time zone from the one our clients are
located at (a Belgium related site is in a server located is USA for example).

First we must know the time in the server. We will create a text file with the code bellow, and we will copy
it to our server:

Time in server: <?php print date("H:i") ?>

Then we will visit our page and we will get the time in the server. Let suppose the time is 16:00

Second, we will calculate the difference in hours between local time and the time in server. Let suppose
the time in Belgium is 20:00, so the difference is 4 hours.

To get the local time we will use the code in the table bellow:
<?php
$differencetolocaltime=4;
$new_U=date("U")-$differencetolocaltime*3600;
print date("H:i", $new_U);
?>

9
Lets explain this code:

• We have create a variable named $differencetolocaltime, and we have stablish the value for this
variable (4)
• In third line of the script we have create a variable named $new_U, and the value for this variable
will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have substracted the
difference of hours between the two time zones (in our case 4 hours, which is the value for the
variable $differencetolocaltime, has been multiplied by 3600, which is the number of seconds in
one hour)
• In the last step we have write to the document the new hour and time by using "date" command to
which we have let know the exact date (specified by $new_U) from which we want to get the time
(if it is not specified, as for example when using 'date("H:i")', the time and date in the server will
be displayed as shown before in this page).

GET and POST methods and how to get info from them

There are two ways we may get info from users by using a form: GET and POST methods. Additionally,
GET method may be used for other porpoises as a regular link. Let´s check both methods

Post method
Get method
An example: three versions

POST method

This method will be indicated in the form we are using to get information from user as shown in the
example bellow

<form method="POST" Your name


action="GetandPost.php">
Your name<BR> Your age
<input type=text name=thename
size=15><BR>
Does not work
Your age<BR>
<input type=text name=theage
size=15><BR>
<input type=submit value="Send info">
</form>

When submitting the form we will visit the URL bellow (will be different when using GET method):

http://www.phptutorial.info/learn/GetandPost.php
When getting information from the form in the response page we will use $_POST command

10
Code Output
<?php print $_POST["thename"]; ?> John
<?php print $_POST["theage"]; ?> 30
<?php Hi John, I know you are 30 years old
$thename=$_POST["thename"];
$theage=$_POST["thename"];

print "Hi ".$thename.", I know you are ".$theage."


years old";
?>

GET method

This method may be used exactly as in the example above, but the URL we will visit after submission will
be diferent.

In the example bellow we have removed the word "POST" and "GET" has been written instead.

<form method="GET" action="GetandPost.php"> Your name


Your name<BR>
<input type=text name=thename size=15><BR> Your age
Your age<BR>
<input type=text name=theage size=15><BR>
Does not work
<input type=submit value="Send info">
</form>

When submitting the form we will visit the URL bellow:

http://www.phptutorial. info/learn/GetandPost.php?thename=John&theage=30
When getting information from the form in the response page we will use $_GETcommand.

Code Output
<? print $QUERY_STRING; ?> thename=John&theage=30
<?php print $_GET["thename"]; ?> John
<?php print $_GET["theage"]; ?> 30
<?php Hi John, I know you are 30 years old
$thename=$_GET["thename"];
$theage=$_GET["thename"];

print "Hi ".$thename.", I know you are ".$theage."


years old";
?>

11
An example: three versions

Get method may be used for additonal porposes. Although Post method is not used in this example, a
similar page may be create. In the example bellow it is shown data in different ways depending
on $QUERY_STRING or $_GET values obtained from the the url visited.

Getandpostexample.php
Getandpostexample.php
<html>
<body bgcolor=FFFFFF>
<pre>
<b>Information about my friends</b>

<?php if ($QUERY_STRING=="showall") { ?>


Anna
From London. Student
Paolo
From Roma. Student
Andoni
From Donosti. Student

<a href=Getandpostexample.php>Hide data</a>


<?php }else{ ?>
<?php if ($_GET["name"]=="Anna") { ?>
Anna
From London. Student
<?php }else{ ?>
<a href=Getandpostexample.php?name=Anna>Anna</a>
<?php } ?>
<?php if ($_GET["name"]=="Paolo") { ?>
Paolo
From Roma. Student
<?php }else{ ?>
<a href=Getandpostexample.php?name=Paolo>Paolo</a>
<?php } ?>
<?php if ($_GET["name"]=="Andoni") { ?>
Andoni
From Euskadi. Student
<?php }else{ ?>
<a href=Getandpostexample.php?name=Andoni>Andoni</a>
<?php } ?>
<p>
<a href=Getandpostexample.php?showall>Show all data</a>

<?php } ?>
</pre>
</body>
</html>
12
The previous code and this one will produce the same result. Just compare them: instead of using open and
close tags each time, print command is used. Line breaks ("\n") are included within the text to be printed.

Getandpostexample2.php
<?php
// this code is always shown
print "<html>\n<body bgcolor=FFFFFF>\n";
print "<pre>\n<b>Information about my friends</b>\n";

if ($QUERY_STRING=="showall") {
print "\nAnna\n From London. Student";
print "\nPaolo\n From Roma. Student";
print "\nAndoni\n From Euskadi. Student";
print "\n<a href=Getandpostexample.php>Hide data</a>";
}else{

if ($_GET["name"]=="Anna") {
print "\nAnna\n From London. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>";
}

if ($_GET["name"]=="Paolo") {
print "\nPaolo\n From Roma. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>";
}

if ($_GET["name"]=="Andoni") {
print "\nAndoni\n From Euskadi. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>";
}

print "\n<a href=Getandpostexample.php?showall>Show all data</a>";

?>
</pre>
</body>
</html>

13
his third version uses three variables named $Anna, $Paolo and $Andoni, which are defined in first tree
lines of the code. Using variables may be a very interesting option in cases like this one.

Getandpostexample3.php
<?php
// Variables are defined for each person
$Anna = "\nAnna\n From London. Student";
$Paolo = "\nPaolo\n From Roma. Student";
$Andoni = "\nAndoni\n From Euskadi. Student";

// this code is always shown


print "<html>\n<body bgcolor=FFFFFF>\n";
print "<pre>\n<b>Information about my friends</b>\n";

if ($QUERY_STRING=="showall") {
print $Anna.$Paolo.$Andoni;
print "\n<a href=Getandpostexample.php>Hide data</a>";
}else{

if ($_GET["name"]=="Anna") {
print $Anna;
}else{
print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>";
}

if ($_GET["name"]=="Paolo") {
print $Paolo;
}else{
print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>";
}

if ($_GET["name"]=="Andoni") {
print $Andoni;
}else{
print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>";
}

print "\n<a href=Getandpostexample.php?showall>Show all data</a>";

}
?>
</pre>
</body>
</html>

14
PHP tutorial: Using arrays
Introduction
Working with Arrays
Selecting values from a array
Creating a table from data in a string
Simple keyword search

Introduction
Instead of having our information (variables or numbers) in variables like $Mydata1, $Mydata2,
$Mydata3 etc, by using arrays our information may be contained in an unique variable. Very often, we will
create an array from data obtained from a table with only one column. Let´s check an example:

array.asp
<html> 1 Original table for the array in the script
<title>My Array</title> 2
<body> 3
MyData
4
<?php 5 0 1
$MyData [0] = "0" 6
$MyData [1] = "1" 7 1 4
$MyData [2] = "2" 8
$MyData [3] = "3" 9 2 7
$MyData [4] = "4" 10 3 3
$MyData [5] = "5"
$MyData [6] = "6" 11 4 4
$MyData [7] = "7" 12
$MyData [8] = "8" 5 5
$MyData [9] = "9" 13
6 6
print $MyData [5]; 14 7 7
?>
15 8 8
</body>
</html> 16 9 9
In the response page we will print the
value assigned to $MyData [5] in the array. The response
17
page will return 5.
18

19

20
21

15
An array may be created from a two dimentional table. Let´s check an example:

array2.php
<html> We may consider the table bellow as the source of
<title>My Array</title> information to create an array named $Mydata.
<body>
MyData 0 1 2
<?php
$MyData [0][0] = "1"; 0 1 2 3
$MyData [0][1] = "2";
$MyData [0][2] = "3"; 1 4 5 6
$MyData [1][0] = "4";
$MyData [1][1] = "5"; 2 7 8 9
Lines 6-14. Values have assigned to
$MyData [1][2] = "6"; the array.
$MyData [2][0] = "7";
$MyData [2][1] = "8"; Line 16. In the response page we will send the value
$MyData [2][1] = "9"; assigned to $MyData [1][2] in the array. The first number
will be the row and the second one the column, so that in our
print $MyData [1][2]; case the response page will show the value "6"
?>

</body>
</html>

An array may be created from a two dimentional table. Let´s check an example:
array2.php
<html> We may consider the table bellow as the source of
<title>My Array</title> information to create an array named $Mydata.
<body>
MyData 0 1 2
<?php
$MyData [0][0] = "1"; 0 1 2 3
$MyData [0][1] = "2";
$MyData [0][2] = "3"; 1 4 5 6
$MyData [1][0] = "4";
$MyData [1][1] = "5"; 2 7 8 9
Lines 6-14. Values have assigned to
$MyData [1][2] = "6"; the array.
$MyData [2][0] = "7";
$MyData [2][1] = "8"; Line 16. In the response page we will send the value
$MyData [2][1] = "9"; assigned to $MyData [1][2] in the array. The first number
will be the row and the second one the column, so that in our
print $MyData [1][2]; case the response page will show the value "6"
?>

</body>
</html>

It is also possible to define an array with more dimensions as for example $MyData [5][5][5][5][5].
16
Working with Arrays
In the examples above we have defined all the values within the script one by one, but this assignation
may be done in a different way, as it is described in the example bellow:

array3a.php Resulting page


<pre> Thearray(0): Zero
<? Thearray(1): pne
$MyArray= array ("Zero","one","two","three","four","five","six","seven","eight","nine") Thearray(2): two
?> Thearray(3): three
Thearray(4): four
Thearray[0]: <? print $Thearray[0]; ?> Thearray(5): five
Thearray[1]: <? print $Thearray[1]; ?> Thearray(6): six
Thearray[2]: <? print $Thearray[2];?> Thearray(7): seven
Thearray[3]: <? print $Thearray[3]; ?> Thearray(8): eight
Thearray[4]: <? print $Thearray[4]; ?> Thearray(9): nine
Thearray[5]: <? print $Thearray[5]; ?>
Thearray[6]: <? print $Thearray[6]; ?>
Thearray[7]: <? print $Thearray[7]; ?>
Thearray[8]: <? print $Thearray[8]; ?>
Thearray[9]: <? print $Thearray[9]; ?>

</pre>

In this example the array has been defined as comma separated element (the first element in the array is
element 0 !). The array command has been used to define the array.

We may want to generate an array from a data in a text. In the example bellow, each word in a text will be
stored in an array (one word in each element of the array), and them the array will be printed out (with
command print_r), and finally word number 5 will be shown:

array3b.php Resulting page


<pre> Array
<? (
$TheText="zero one two three four five six seven eight nine"; [0] => zero
$Thearray=split (" ",$TheText) ; [1] => one
[2] => two
print_r ($Thearray); [3] => three
?> [4] => four
[5] => five
[6] => six
<hr>
[7] => seven
The element number 5 is : <? print $Thearray[5]; ?>
[8] => eight
[9] => nine
</pre>
)
The element number 5 is :
five

In this example we have defined the variable $TheText, and whithin this variable we have include several
words separated by spaces.
17
In the next line, we have splitted the variable $TheText into an array named $Thearray.
Split command have been used to brake $TheText and " " (space) has been used as a delimiter to separate
the substrings.

In the response page we have printed the array by using command print_r, and element number 5 has been
printed out.

It may happend to have a string we want to split, but we do not know how many substrings we may get. In
that case we may use command sizeof to discover how many elements are in our array, and them we may
use that value to write them by using a foreach control structure (see example below).

array4.php Resulting page


<pre> How many words do I have in
<? $TheArray?
$TheText="my dog is very nice and my cat is barking"; 10
$Thearray=split (" ",$TheText) ;
?> Word number 0 is my
Word number 1 is dog
How many words do I have in $TheArray? Word number 2 is is
<? print sizeof ($Thearray); ?> Word number 3 is very
Word number 4 is nice
Word number 5 is and
<? Word number 6 is my
Foreach ($Thearray as $key =>$val){ Word number 7 is cat
print "<br>Word number $key is $val"; Word number 8 is is
} Word number 9 is barking
?>

</pre>

18
Selecting values from a array
In the next example we will count number of element in the array containing the word "o". Two methods
will be used

array5.php Resulting page


<pre> Method 1:
<? Number of
$MyArray [0] = "Zero"; strings
$MyArray [1] = "One"; containing "o"
$MyArray [2] = "Two"; (case
$MyArray [3] = "Three"; sensitive)
$MyArray [4] = "Four"; 3
$MyArray [5] = "Five"; Number of
$MyArray [6] = "Six"; strings
$MyArray [7] = "Seven"; containing "o"
$MyArray [8] = "Eight"; (case
$MyArray [9] = "Nine"; insensitive)
4

?> Method 2:
<b>Method 1</b>: Number of
Number of strings containing "o" (case sensitive) strings
<? containing "o"
$counter=0; (case
foreach ($MyArray as $key =>$val){ sensitive)
3
if (substr_count ($val,"o")>0){$counter++;}
Find strings
}
containing "o"
print $counter;
(case
?>
insensitive)
4
Number of strings containing "o" (case insensitive)
<?
$counter=0;
foreach ($MyArray as $key =>$val){
if (substr_count ($val,"o")>0 or substr_count($val,"O")>0){$counter++;}
}
print $counter;
?>

<b>Method 2</b>:
Number of strings containing "o" (case sensitive)
<?
$MyNewArray=preg_grep ("/(o)/",$MyArray);
print sizeof($MyNewArray);
?>

Find strings containing "o" (case insensitive)


<?
$MyNewArray=preg_grep ("/(o|O)/",$MyArray);
print sizeof($MyNewArray);
?>

</pre>
19
In the first method, we check all elements in the array (by using foreach control structure), and in each
element we will count number of times the letter "o" is present ( by using command substr_count and a
variable named $counter). At the end of the process $counter is printed out.

In the second method a new array is created from $MyArray by using a preg_grep command. This
command will extract to the new array ($MyNewArray) the elements contained in array the original array
by using a pattern. Learning about pattern syntax is very important for mediu and advances programers.
Here, we just want to let the visitor know this concept. The second method will print the size of the newly
created array, which is the number of elements containing the letter "o" within array $MyArray.

Creating a table from data in a string


In order to undertand this script we will consider we have a table like the one bellow, and that this table
was the original source of information we used to create our table:

Peter student Chicago 123


John teacher London 234
Sue Manager Sidney 789
From the table we got this three lines by separeting the values by commas:

Peter,student,Chicago,123
John,teacher,London,234
Sue,Manager,Sidney,789

And finaly we conected the three lines by separeting the values with "/":

Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789

The string obtained was saved to a variable named $Mydata in the script bellow. The resulting page will
show a table similar to the original one. This script is not limited by number of rows or columns (the
maximun amount of then is calculate each time we run the script), so we may change information stored in
variable $Mydata, and a table with correct dimensions will be created.
Createatable.php
<?
$Mydata="Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789";
Createtable($Mydata);

function CreateTable($Mydata){
$MyRows=split ("/", $Mydata);
$NumberRows=sizeof($MyRows);

print "<table border=1>"; // start printing out the table

20
// data contained in each element at array $myRows
// is printed to one line of the table
foreach ($MyRows as $row){
$datainrow=split (",", $row);
print "<tr>"; // start printing a row
foreach ($datainrow as $val){
print "<td>$val</td>"; // print data in the row
}
print "</tr>"; // end printing the row
}
print "</table>"; // end printing out the table
}

?>

This script may be used for several porpouses: we may generate $Mydata by filtering values from an array
as shown bellow:

<?
$query="Chicago";

$Myclients [0]="Peter Smith,Chicago,Manager,123";


$Myclients [1]="John Smith,New York,Accountant,124";
$Myclients [2]="George Smith,Chicago,Administration,245";
$Myclients [3]="Sam Smith,Dallas,Consultant,567";

$Mydata=="";
foreach ($Myclients as $val){
if (substr_count ($val,$query)>0){$Mydata.=$val."/";}
}

Createtable($Mydata);
?>

This code in combination with Createtable() function in the previus example will display only the clients
from Chicago. The $query variable may be obtained from a form.

21
Simple keyword search
In this example, in our first visit a form asking for a keyword will be display. After submitting the
keyword Redirect() function will be activated.
In function Redirect we have create an array named $Websites. This array contains the url of websites and
a its short description. In case the query string is included in the description of the site, the visitor will be
redirected to the corresponding URL.
search.php
<?
if ($_POST){ // check whether info has been posted
$query=$_POST["query"];
Redirect($query);

}else{ // if no info has been posted, print the form


print "<form method=post action=search.php>";
print "<input type=text name=query>";
print "<input type=Submit value=Search>";
print "</form>";
}

function Redirect($query){

// Array containing containing URLs and descriptions


$Websites [0]["url"] = "http://www.phptutorial.info";
$Websites [0]["description"] = "Main page of PHPTutorial.info";

$Websites [1]["url"] = "http://www.phptutorial.info/scripts/Contact_form.html";


$Websites [1]["description"] = "Contact form script";

$Websites [2]["url"] = "http://www.phptutorial.info/scripts/Hit_counter.html";


$Websites [2]["description"] = "Simple hit counter script";

$Websites [3]["url"] = "http://www.phptutorial.info/iptocountry/";


$Websites [3]["description"] = "Free script and databse for country identification based on IP address";

// find query string within description of websites


foreach ($Website as $key=> $val){
if (substr_count($Website [$key]["description"],$query)>0){
//next line will redirect the user to the corresponding url
header ("Location: ".$Website [$key]["url"]);
exit;
}
}
}
?>

22

You might also like