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>
<title>My Array</title>
<body>

<?php
$MyData [0] = "0"
$MyData [1] = "1"
$MyData [2] = "2"
$MyData [3] = "3"
$MyData [4] = "4"
$MyData [5] = "5"
$MyData [6] = "6"
$MyData [7] = "7"
$MyData [8] = "8"
$MyData [9] = "9"

print $MyData [5];
?>

</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Original table for the array in the script
 MyData  
0
1
1
4
2
7
3
3
4
4
5
5
6
6
7
7
8
8
9
9

In the response page we will print the value assigned to $MyData [5] in the array. The response page will return 5. 
 



An array may be created from a two dimentional table. Let´s check an example:
 
array2.php
<html>
<title>My Array</title>
<body>

<?php
$MyData [0][0] = "1";
$MyData [0][1] = "2";
$MyData [0][2] = "3";
$MyData [1][0] = "4";
$MyData [1][1] = "5";
$MyData [1][2] = "6";
$MyData [2][0] = "7";
$MyData [2][1] = "8";
$MyData [2][1] = "9";

print $MyData [1][2];
?>

</body>
</html>

We may consider the table bellow as the source of information to create an array named $Mydata.  
 MyData
0
1
2
0
1
2
3
1
4
5
6
2
7
8
9

Lines 6-14. Values have assigned to the array. 

Line 16. In the response page we will send the value 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 case the response page will show the value "6"
 

It is also possible to define an array with more dimensions as for example  $MyData [5][5][5][5][5].

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= array ("Zero","one","two","three","four","five","six","seven","eight","nine")
?>

Thearray[0]: <? print $Thearray[0]; ?>
Thearray[1]: <? print $Thearray[1]; ?>
Thearray[2]: <? print $Thearray[2];?>
Thearray[3]: <? print $Thearray[3]; ?>
Thearray[4]: <? print $Thearray[4]; ?>
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>

Thearray(0): Zero
Thearray(1): pne
Thearray(2): two
Thearray(3): three
Thearray(4): four
Thearray(5): five
Thearray(6): six
Thearray(7): seven
Thearray(8): eight
Thearray(9): nine
 

 

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>
<?
$TheText="zero one two three four five six seven eight nine";
$Thearray=split (" ",$TheText) ;

print_r ($Thearray);
?>

<hr>
The element number 5 is : <?  print $Thearray[5];  ?>

</pre>

Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
[8] => eight
[9] => nine
)

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.

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>
<?
$TheText="my dog is very nice and my cat is barking";
$Thearray=split (" ",$TheText) ;
?>

How many words do I have in $TheArray?
<? print sizeof ($Thearray); ?>

<? 
Foreach ($Thearray as $key =>$val){ 
  print "<br>Word number $key is $val";

?>

</pre>

How many words do I have in $TheArray?
10

Word number 0 is my
Word number 1 is dog
Word number 2 is is
Word number 3 is very
Word number 4 is nice
Word number 5 is and
Word number 6 is my
Word number 7 is cat
Word number 8 is is
Word number 9 is barking

 

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>
<?
$MyArray [0] = "Zero";
$MyArray [1] = "One";
$MyArray [2] = "Two";
$MyArray [3] = "Three";
$MyArray [4] = "Four";
$MyArray [5] = "Five";
$MyArray [6] = "Six";
$MyArray [7] = "Seven";
$MyArray [8] = "Eight";
$MyArray [9] = "Nine";


?>
<b>Method  1</b>:
Number of strings containing "o" (case sensitive)
   <?
   $counter=0;
  
foreach ($MyArray as $key =>$val){
        if (substr_count ($val,"o")>0){$counter++;}
   }
   print $counter;
   ?>
   
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>
Method 1:
Number of strings containing "o" (case sensitive)
3
Number of strings containing "o" (case insensitive)
4

Method 2:
Number of strings containing "o" (case sensitive)
3
Find strings containing "o" (case insensitive)
4

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

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

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

}
?>

 

Tutorial home page

  PHPTutorial.info.