Array Variables

As stated in the variables section, variables are containers for your data. For example, I can say that the variable $student is set equal to "Julio Garcia."

$student="Julio Garcia";

I can then tell PHP to print($student); and PHP will print: Julio Garcia.

print($student);

That's easy enough, but I can take things a step further. I can say that:

$student[0]="Alicia Diaz ";
$student[1]="Raul Garcia ";
$student[2]="Rigo Delacruz ";

This kind of variable, a variable that can hold more than one value, is called an array. Therefore, we can define an array as a collection of values stored under a single variable name. Notice that each value in the array is numbered. We call this number the index and the value an element.

We can also provide strings (characters) for index values, like so:

$class["seniors"]=200;
$class["juniors"]=200;
$class["sophomores"]=400;
$class["freshmen"]=400;

An easier way to set array values is:

$shoppinglist("milk", "cookies", "cereal", "bread");

This will create an index of 0 through 3 which correspond to each shopping list value, like so:

$shopping[0]="milk";
$shopping[1]="cookies";
$shopping[2]="cereal";
$shopping[3]="bread";

So why are arrays important? We will need to loop through values of the $_REQUEST array in order to get form values submitted by users.

Here's an array example: arrayvariables.php



<html>
<head>
<title>arrayvariables.php</title>
</head>
<body>


<p>My eight Web 2 students have just taken their final exam.  
It was very difficult so I decided to buy my 'A' students a new car. 
Here are their scores: </p> 

Student1: 89.4<br>
Student2: 89<br>
Student3: 90<br>
Student4: 91<br>
Student5: 89.3<br>
Student6: 92<br>
Student7: 99<br>
Student8 :99.9<br>


<p>Let's use PHP to display the great news.  
We will use an array to store the values.</p>
<?php
//This is the array to hold the grades
//notice that arrays are usually numbered 
//begining with zero.  This is called a zero index.
$grades[0]= 89.4;
$grades[1]= 89;
$grades[2]= 90;
$grades[3]= 91;
$grades[4]= 89.3;
$grades[5]= 92;
$grades[6]= 99;
$grades[7]= 99.9;

//Let's display the number of grades in the array
//by using the echo command and the count function.
//count() returns the number of items within the parenthesis
echo "<p>";
echo 
"There are ".count($grades)." grades in the array.";
echo 
"</p>";

//Here are the statements to test 
//whether students scored greater than 89.5 (I round up).
//Let's get fancy and use a for loop

//counter variable: Set the counter variable to zero 
//condition:run the code while the counter variable is less than 8
//REMEMBER there are 8 students, but we indexed at zero!
//counter increment: increase the counter on every loop

for ($counter=0$counter count($grades) ; $counter=$counter+1)
{
    if (
$grades[$counter] >89.5)
    {
    
//must add one to counter because index starts at zero
    
print("A new car for student ".($counter+1)."!<br>");
    }
}
?>

</body>
</html>