分类:
2009-04-23 12:13:02
Understanding arrays is the first major milestone when learning how to code. An array is not an easy concept to grasp at first since an array has many values, or elements, and can be used in so many ways. Many functions return their results as an array. There is no way around it, if you want to learn how to code, be it in php, javascript or any other language, you will need to understand the array.
A common definition for an array is a list used to organize or group elements. This is, to some degree, an accurate definition. Arrays share many characteristics of a list, but list can only be used to organize items and arrays can do a bit more. A better definition would be that an array is a container where you can organize, group and store items. The big difference being that a container holds the actual items and a list only is a reference of the items. If I give you a list of my tools all you can do is reorganize the list for your own use, but if I give you a box with my tools you can reorganize, borrow, add a new one and then give the box back to me with the modifications you made.
There are two types of : Numerical Arrays (also referred to as Indexed Arrays) and Associative Arrays. However, php does not treat the two types any differently, as far as php is concerned they are both simply arrays.
There are also Multidimensional Arrays, which are arrays, either numerical or associative that have arrays as values (in other words multiple values).
At first glance an array is very similar to a variable, we identify it with a $ and give it a name.
1.
$variableName
It is when assigning an array’s values that things change. PHP is very flexible and you do not need to declare a variable as an array before using it but we do need to use the correct syntax. The method for defining an array is with the following syntax:
1.
$arrayName
=
array
(
"value-1″,"
value-2″,"value-3″)
You can also set each array item individually by using the square bracket syntax:
1.
$arrayName
[] =
"value-1"
;
2.
$arrayName
[] =
"value-2"
;
3.
$arrayName
[] =
"value-3"
;
Both methods will result in the same array $arrayName containing the 3 set values. You can even mix the two methods:
1.
$arrayName
=
array
(
"value-1″,"
value-2″,"value-3″);
2.
$arrayName
[] =
"value-4"
;
3.
$arrayName
[] =
"value-5"
;
This will result in the $arrayName array having 5 indexed values value-1 to value-5.
note: You could also use the function to add elements to an array.
note: array values can be strings, integers or arrays.
In an array each value gets a unique index, or key assigned to it. In order to return a specific value from the array you need to identify the element by its key. The format of the index key is what defines the type of array. In a numerical array the key is defined by a unique numeric id. If no key value is defined when assigning the array values then php will default to a numerical array. In the previous example we created a numerical array. To get a better understanding let’s look inside this array.
We can view an array’s contents by using the function. This function is very useful when debugging arrays since it lets you look inside an array’s structure and see it’s element’s key/value relationships. If we run print_r on the array we have just created it will output:
note: wrap the output of print_r with tags for readable formating
1.
Array
2.
(
3.
[0] => value-1
4.
[1] => value-2
5.
[2] => value-3
6.
[3] => value-4
7.
[4] => value-5
8.
)
The index key is displayed in the square bracket [3] and the corresponding value is displayed after the arrow =>. Examine the array output and you will notice two important factors:
Now that we know the index key that corresponds to the value we want to retrieve from the array we can use the key to isolate the element we want. We know that “value-2″ corresponds to index key 3, and we can echo this value with the following syntax:
1.
echo
$arrayName
[3]
In an associative array the index key is defined by a string rather than an integer. This is a very powerful feature since this will allow us to associate a descriptive key to identify the value as opposed to a non-descriptive number. Associative arrays are set by assigning key => value pairs for each array element. We can use the array() or square bracket format to define an associative array:
1.
$arrayName
=
array
(
"key1"
=>
"value-1"
,
"key2"
=>
"value-2"
);
2.
// or use square braket sytax
3.
$arrayName
[
"key3"
] =
"value-3"
;
4.
$arrayName
[
"key4"
] =
"value-4"
;
Notice the difference when we output the array structure with print_r, the keys are the values that we defined and not numerical:
1.
Array
2.
(
3.
[key1] => value-1
4.
[key2] => value-2
5.
[key3] => value-3
6.
[key4] => value-4
7.
)
We access the array values in the same way we do with numerical arrays. To return the value of the array element with the key of "key2" we would:
1.
echo
$arrayName
[
"key2"
];
You can see how this can be very useful if we use descriptive keys:
1.
$dinner
[
"drink"
] =
"red wine"
;
2.
$dinner
[
"food"
] =
"steak"
;
3.
$dinner
[
"desert"
] =
"apple pie"
;
note: you can mix numeric and associative keys in the same array.
We have seen how to return individual values from an array. However, there will be occasions where you will want to go through the structure of an array to interact with the array values. The loop is the most common method for iterating through an array. It works like a loop that will go through the array and provides a method for you to extract the value or the key => value pair for each array element. The syntax for the foreach function is:
1.
foreach
(
array
as
$value
) {
2.
...
3.
}
Or for returning the key and the value:
1.
foreach
(
array
as
$key
=>
$value
){
2.
...
3.
}
Let’s see how we can use an array with the foreach loop to generate a link menu. First we create an array to store the information for out menu. The info we need is the link text and the link url. For this we will use an associative array and take advantage of the key value as the link text.
1.
$myMenu
[
"home"
] =
"home.html"
;
2.
$myMenu
[
"about"
] =
"pages/about-us.html"
;
3.
$myMenu
[
"services"
] =
"internet/services.html"
;
4.
$myMenu
[
"contact"
] =
"form/contact.html"
;
Now we can use the foreach loop to build the menu output:
This will output our menu as:
So far we have worked with simple arrays where there is one key corresponding to a single ‘value’ for each array element. However, what happens if we need more than one key=>value pair per element? We can handle this by using an array as the value for an element so that one key can have multiple values based on a second key layer, or dimension. Like those cool boxes that you open and there is another box inside it.
Expanding on the previous link menu example we can modify the array to include additional fields for our menu.
1.
$myMenu
[
"home"
] =
array
(
"url"
=>
"home.html"
,
"text"
=>
"Home Page"
);
2.
$myMenu
[
"about"
] =
array
(
"url"
=>
"pages/about-us.html"
,
"text"
=>
"About Us"
);
3.
$myMenu
[
"services"
] =
array
(
"url"
=>
"internet/services.html"
,
"text"
=>
"Our Services"
);
4.
$myMenu
[
"contact"
] =
array
(
"url"
=>
"form/contact.html"
,
"text"
=>
"Contact Us"
);
To get a clear view of how this array is structured lets look at it with :
01.
Array
02.
(
03.
[home] => Array
04.
(
05.
[url] => home.html
06.
[text] => Home Page
07.
)
08.
09.
[about] => Array
10.
(
11.
[url] => pages/about-us.html
12.
[text] => About Us
13.
)
14.
15.
[services] => Array
16.
(
17.
[url] => internet/services.html
18.
[text] => Our Services
19.
)
20.
21.
[contact] => Array
22.
(
23.
[url] => form/contact.html
24.
[text] => Contact Us
25.
)
26.
27.
)
Notice that there are multiple values available for each top level element. We can access the values within the array directly by including the subsequent index key to the array name:
1.
echo
"{$myMenu['home']['text']} "
;
Notice that we are using the {} around our array, this is the syntax for referencing a complex variable and is referred to as "complex (curly) syntax".
We can iterate through a multidimensional array using the same method as we did with the standard arrays, using the loop and adding additional loops for each level we want to reach in the array:
01.
foreach
(
$myMenu
as
$key
=>
$val
){
02.
foreach
(
$val
as
$k
=>
$v
){
03.
$url
=
$k
;
04.
$link
=
$v
;
05.
}
06.
$output
.=
"$link
\n"
;
07.
}
08.
09.
echo
$output
;
The output will be:
As you can see we were successfully able to include additional data to our array.
PHP has a full set of tools that allow you to manipulate and interact with arrays in virtually any way that is needed. Here are some common functions you should know
Sorting Arrays: PHP has many functions for , the most common are the to sort by ‘value’, or sorting by key.
1.
// sort by value
2.
asort(
$arrayName
);
3.
4.
// sort by key
5.
ksort(
$arrayName
);
note: you can also use the sort() function, but this will not retain the key association to the value.
Checking if a variable is an array: Use to see if a variable is an array.
1.
if
(
is_array
(
$arrayName
){ ... }
Checking if a value is in an arrray: Use to see if a value is in an array.
1.
if
(in_array(
"value"
,
$arrayName
)){ ... }
How many elements in an array: Use to return the number of elements in an array.
1.
echo
count
(
$arrayName
);
How many elements in a multidimensional array: Use the second parameter for to enter COUNT_RECURSIVE mode.
1.
echo
count
(
$arrayName
, 1);
There are many more, be sure to check out the php documentation on for a complete list of the available functions.