linuxStat PHP Documentation

Construction of a data table

A PHP variable is used to hold a single value. For example, we have
used the variable $age to hold the age of Marvin K. Mooney.
However, often it is required to hold a group of related values.
It is a common practice to present these related values in a table.
For example, consider the following table:

First Name Marvin
Middle Name K.
Last Name Mooney
Age 15
G.P.A. 3.9


PHP provides the following notation to support construction
of such tabular representation of data.

Example 12.1:

$mkMooney           = array();    // Line 1
$mkMooney["first"]  = "Marvin";   // Line 2
$mkMooney["middle"] = "K.";       // Line 3
$mkMooney["last"]   = "Mooney";   // Line 4
$mkMooney["age"]    = 15;         // Line 5
$mkMooney["gpa"]    = 3.9;        // Line 6
In Line 1, an empty table is constructed by using the PHP notation array().

In Line 2, the string value "Marvin" is associated with the name first.
This name-value pair constitutes a row of the data table.

Line 3 constructs another row of the data table and associates
the string value "K." with the name middle.

Line 4 constructs another row of the data table and associates
the string value "Mooney" with the name last.

Line 5 constructs another row of the data table and associates
the integer value 15 with the name age.

Line 6 constructs another row of the data table and associates
the float value 3.9 with the name gpa.

The term in computer science for the above structure
provided in PHP to hold a data table is associative array or map.

I will use the term map. This is a term used in mathematics for
the association of a set of values with a set of names.

The PHP program in Example 12.1 embedded in an HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<title>Executed on Dell Server, Intel Processor, created on HP laptop</title>
</head>
<body bgcolor="#6B7E23" text="#FFFF00" lang=EN-US>
<?php
# Example of a map
$mkMooney           = array();    // Line 1
$mkMooney["first"]  = "Marvin";   // Line 2
$mkMooney["middle"] = "K.";       // Line 3
$mkMooney["last"]   = "Mooney";   // Line 4
$mkMooney["age"]    = 15;         // Line 5
$mkMooney["gpa"]    = 3.9;        // Line 6
print "The first name of M. K. Mooney is {$mkMooney["first"]} <br>";
print "The middle name of M. K. Mooney is {$mkMooney["middle"]} <br>";
print "The last name of M. K. Mooney is {$mkMooney["last"]} <br>";
print "M. K. Mooney's age: {$mkMooney["age"]} <br>";
print "M. K. Mooney's G.P.A.: {$mkMooney["gpa"]} <br>";
?>
</body>
</html>

Click the following link to execute the above PHP program
by my server's PHP interpreter.

Try the above example   Next   Index