PHP Chapter 6 (Arrays in PHP)

PHP Arrays

You know what a variable is – just a storage area where you hold numbers and text. The problem is, a variable will hold only one value. You can store a single number in a variable, or a single string. An array is like a special variable, which can hold more than one number, or more than one string, at a time. If you have a list of items (like a list of customer orders, for example), and you need to do something with them, then it would be quite cumbersome to do this:
$Order_Number1 = "Black shoes";
$Order_Number2 = "Tan shoes";
$Order_Number3 = "Red shoes";
$Order_Number4 = "Blue shoes";
What if you want to loop through your orders and find a specific one? And what if you had not four orders but four hundred? A single variable is clearly not the best programming tool to use here. But an array is! An array can hold all your orders under a single name. And you can access the orders by just referring to the array name.
If that's a bit confusing right now, let’s make a start on explaining how arrays work.

How to Set up a PHP Array

In the code on the previous page, we had four items, and all with a different variable name:$Order_Number1, $Order_Number2, $Order_Number3, and $Order_Number4. With an array, you can just use a single name. You set up an array like this:
$Order_Number = array( );
First you type out what you want your array to be called ($Order_Number, in the array above) and, after an equals sign, you type this:
array( );
So setting up an array just involves typing the word array followed by a pair of round brackets. This is enough to tell PHP that you want to set up the array. But there's nothing in the array yet. All we're doing with our line of code is telling PHP to set up an array, and give it the name $Order_Number.
You can use two basic methods to put something into an array.

Method One – Type between the round brackets
The first method involves typing your values between the round brackets of array(). In the code below, we're setting up an array to hold the seasons of the year:
$seasons = array( "Autumn", "Winter", "Spring", "Summer" );
So the name of the array is $seasons. Between the round brackets of array(), we have typed some values. Each value is separated by a comma:
("Autumn", "Winter", "Spring", "Summer")
Arrays work by having a position, and some data for that position. In the above array, "Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in position 3.
The first position is always zero, unless you tell PHP otherwise. But the position is know as a Key. The Key then has a value attached to it. You can specify your own numbers for the Keys. If so, you do it like this:
$seasons = array( 1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer" );
So you type a number for your key, followed by the equals sign and a right angle bracket ( => ). In the array above, the first Key is now 1 and not 0. The item stored under key 1 is "Autumn". The last key is 4, and the item stored under key 4 is "Summer". Careful of all the commas, when you set up an array like this. Miss one out and you'll get error messages. Here's the keys and values that are set up in the array above:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
If you let PHP set the keys for you, it would be this:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
You can have numbers for the values of your keys. Here's an array that stores the numbers 10, 20, 30 and 40.
$Array_Name = array(10, 20, 30, 40);
Because no keys were specified, PHP will set your array up like this:
0=> 10,
1=> 20,
2=> 30,
3=> 40
Here's the same array again, only this time we're specifying our own key:
$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
This array will then look like this:
1=> 10,
2=> 20,
3=> 30,
4=> 40
So the key name is typed before the => symbol, and the data stored under this key is to the right.
You can store text and numbers in the same array:
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer"

Method two – Assign values to an array
Another way to put values into an array is like this:
$seasons = array();
$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";
Here, the array is first set up with $seasons = array();. This tells PHP that you want to create an array with the name of $seasons. To store values in the array you first type the name of the array, followed by a pair of square brackets:
$seasons[ ]
After the equals sign, you type out what you want to store in this position. Because no numbers were typed in between the square brackets, PHP will assign the number 0 as the first key:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
This is exactly the same as the array you saw earlier. If you want different numbers for your keys, then simply type them between the square brackets:
$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";
PHP will then see your array like this:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
This method of creating arrays can be very useful for assigning values to an array within a loop. Here's some code:
$start = 1;
$times = 2;
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
Don't worry if you don't fully understand the code above. The point is that the values in the array called $answer, and the array key numbers, are being assigned inside the loop. When you get some experience with arrays, you'll be creating them just like above!

PHP Array Values

OK, so you now know how to store values in your array. But how do you get at those values? Well, there are few ways you can do it. But the "Key" is the key. Here's an example for you to try:
<?php
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
?>
The array is the same one we set up before. To get at what is inside of an array, just type the key number you want to access. In the above code, we're printing out what is held in the 0 position (Key) in the array. You just type the key number between the square brackets of your array name:
print $Array_Name[0];
You can also assign this value to another variable:
$key_data = $Array_Name[0];
print $key_data;
It's a lot easier using a loop, though. Suppose you wanted to print out all the values in your array. You could do it like this:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
print $seasons[1];
print $seasons[2];
print $seasons[3];
Or you could do it like this:
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
print $seasons[$key_Number];
}
If you have many array values to access, then using a loop like the one above will save you a lot of work!
You don't have to use numbers for the keys - you can use text.

Associative Array in PHP

Your arrays keys don't have to be numbers, as in the previous section. They can be text. This can help you remember what's in a key, or what it's supposed to do. When you use text for the keys, you're using an Associative array; when you use numbers for the keys, you're using a Scalar array. Here's an array that sets up first name and surname combinations:
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
Fans of a certain band will know exactly who these people are! But look at the keys and values now:
David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"
This is easier to remember than this:
0 => "Gilmour",
1 => "Mason",
2 => "Waters",
3 => "Wright"
To access the values in an Associative array, just refer to the Key name:
print $full_name["David"];
However, because Associative arrays don't have numbers for the keys, another technique is used to loop round them – the For Each loop.

Arrays and PHP For Each Loops

In the previous section, you saw what a Associative array was, and that they use text as the Key. In this lesson, you'll learn how to access each element in Associative array - with the For Each loop. So study the following code (try it out in a script):
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
foreach ($full_name as $key_name => $key_value) {
print "Key = " . $key_name . " Value = " . $key_value . "<BR>";
}
The For Each loop is a little more complex than other loops you've met. In the script above, we set up the array as normal. But the first line of the loop is this:
foreach ($full_name as $key_name => $key_value) {
Notice that the name of the loop is one word: foreach and NOT for each. Next comes the round brackets. Inside of the round brackets, we have this:
$full_name as $key_name => $key_value
You start by typing the name of the array you want to loop round. For us, that was $full_name. Next is this:
as $key_name => $key_value
This means, "Get the Key and its Value from the array called $full_name. The Key is called $key_name in the script above, and the value is called $key_value. But these are just variable names. You can call them almost anything you like. Would could have had this:
foreach ($full_name as $first_name => $surname) {
When you use foreach, PHP knows that it's accessing the key name first and then the key value. It knows this because of the => symbol between the two. It then returns the values into your variable names, whatever they may be.
Once your loop code is executed (a print statement for us), it then loops round and returns the next Key/Value pair, storing the results in your variables.
If you need to access values from an Associative array, then, use a foreach loop.

Sorting PHP Array values

There may be times when you want to sort the values inside of an array. For example, suppose your array values are not in alphabetical order. Like this one:
$full_name = array();
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
$full_name["Nick"] = "Mason";
$full_name["David"] = "Gilmour";
To sort this array, you just use the assort( ) function. This involves nothing more complex than typing the word asort, followed by round brackets. In between the round brackets, type in the name of your Associative array:
asort( $full_name );
The letter "a" tells PHP that the array is an Associative one. (If you don't have the "a" before "sort", your key names will turn in to numbers!). The "a" also tells PHP to sort by the Value, and NOT by the key. In our script above, the surnames will be sorted. If you want to sort using the Key, then you can use ksort() instead.
If you have a Scalar array (numbers as Keys), then you leave the "a" off. Like this:
$numbers = array( );
$numbers[ ]="2";
$numbers[ ]="8";
$numbers[ ]="10";
$numbers[ ]="6";
sort($numbers);
print $numbers[0];
print $numbers[1];
print $numbers[2];
print $numbers[3];
The numbers are then sorted from lowest to highest. If you want to sort in reverse order then you need the following:
rsort( ) – Sorts a Scalar array in reverse order
arsort( ) - Sorts the Values in an Associative array in reverse order
krsort( ) - Sorts the Keys in an Associative array in reverse order

Get a Random Key from a PHP Array

You can grab a random key from an array. This could be useful in games of chance. Here's a simple script that simulates a single dice throw:
<?PHP
$numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
$random_key = array_rand($numbers, 1);
print $random_key;
?>
The function that returns the random key is this:
array_rand($numbers, 1);
You start off with the function array_rand( ). In between the round brackets, you need two things: the name of your array, and how many random keys you want to grab.
Try the script out. Refresh the page and you should see a different number between 1 and 6 display.

The PHP count function

The count( ) function is useful when you want to return how many elements are in your array. You can then use this in a for loop. Here's an example we used earlier, only this time with the count function:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
$array_count = count($seasons);
for ($key_Number = 0; $key_Number < $array_count; $key_Number++) {
print $seasons[$key_Number];
}
To get how many elements are in the array, we used this:
$array_count = count($seasons);
So you type the word count and then the round brackets. In between the round brackets, you type the name of your array. The function then counts how many elements are in the array, which we then assign to a variable called $array_count. You can then use this value as the end condition in you loop:
for ($key_Number = 0; $key_Number < $array_count; $key_Number++)
Here, we're saying, "keep looping round as long as the value in $key_Number is less than the value in $array_count.


Some PHP array scripts

To give your more practice using arrays, there are some scripts for you to try out. The scripts are amongst the files you downloaded (in the scripts folder). The file you're looking for is called scripts.txt. You can also copy and paste the scripts by clicking on the links below.
Script One - Set up an array and print out the values (<?PHP
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0] . " ";
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3];
?>
)

Script Two - Set up an array with your own Keys (<?PHP
$seasons = array(1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer");
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3] . " ";
print $seasons[4];
?>
)

Script Three - Set up an array with mixed values (<?PHP
$seasons = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3] . " ";
print $seasons[4];
?>
)

Script Four - Assign values to an array: Method Two example (<?PHP
$seasons = array();
$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";
print $seasons[0] . " ";
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3];
?>
)

Script Five - Looping round values in an array (<?PHP
$start = 1;
$times = 2;
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
print $answer[1] . " ";
print $answer[4] . " ";
print $answer[8] . " ";
print $answer[10];
?>
)

Script Six - Looping round values in an array: example 2 (<?PHP
$seasons = array("Autumn", "Winter", "Spring", "Summer");
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
print $seasons[$key_Number];
}
?>
)

Script Seven - Using text as Keys (<?PHP
$full_name = array();
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
print $full_name["Nick"] . "<BR>";
print $full_name["David"];
?>
)

Script Eight - Looping round an Associative array using For Each (<?PHP
$full_name = array();
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
?>
)

Script Nine - Sorting Arrays (Associative) (<?PHP
$full_name = array();
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
$full_name["Nick"] = "Mason";
$full_name["David"] = "Gilmour";
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
print "<P>";
ksort($full_name);
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
?>
)

Script Ten - Sorting Arrays (Scalar) (<?PHP
$numbers = array();
$numbers[ ]="2";
$numbers[ ]="8";
$numbers[ ]="10";
$numbers[ ]="6";
sort($numbers);
print $numbers[0] . " ";
print $numbers[1] . " ";
print $numbers[2] . " ";
print $numbers[3];
?>
)

In the next section, we'll move on to String Manipulation with PHP.

Comments