- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
A Server Side Web Tutorial #5 - Working with PHP Indexed, Associative, and Multidimensional Arrays
Recap of Our Last Tutorial & This Tutorial's Goals
In our last tutorial, A Server Side Web Tutorial Series # 4 - PHP Conditional Statements we introduced all of the operators in the PHP language suite. One of the operators the union operator works exclusively on arrays. Other comparison operators work with arrays in a similar fashion as they do with other variables (e.g. equality, inequality). As far as conditional statements, again, there is one, the foreach looping statement is used exclusively with arrays. We presented an example of the foreach loop appealing to the readers intuitive reason knowing that in this tutorial we would be presenting a more rigorous treatment of array.
In this array we will indicate what arrays are, how to create them, go through a more formal presentation of the foreach statement, and demonstrate a number of PHP built-in functions which manipulate arrays.
What is an array? Why are arrays useful?
An array is a special variable which may has more than one value related to it. Consider the following example . Suppose our program had to store data about vegetables. One coul start out with:
$veg1 = "carrots";
$veg2 = "spinach";
$veg3 = "lima beans";
Now, let's suppose that you were developing a computer program which need to get the dollar value of all of the vergetables you had in stock. You would have to address each vegetable by a specific name $veg1,, veg2,....,etc. and then somehow manipulate another list with the vegetable price, $vegcost1, vegcost2,.....etc and then have a third set of variables which were related to amount of that vegetable that you had in stock. So, to compute your inventory at.cost you would have 3 unique variables for each vegetable times the number of vegetables.The coding of such an example could run into several hundreds if not thousands of lines.
Arrays were developed for just this type of problems.Arrays can hold many values under one name. In our situation we could have only three varible names for our example regardless of the number of vegetables we needed to keep track of: $vegetableName, $vegetableCost, and $vegetableAmount. Better yet, when we discuss multidimensional arrays we could refer to all of this information with one variable, $vegetable, in three dimensions.
Creating an Array
In PHP, the keyword array is used to create an array. There are three types of arrays in PH (from simplest to most complex):
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
Ways to Create an Indexed Arrays
There are two ways to create arrays. For our vegetable example:
$vegetable = array("beans", "beets", "corn", "squash",);
that is select a variable name performing an assignment using the keyword array, and in parenthesis for string have the various items in quotes separated by commas. For numeric arrays it would just be the numeric values separated by commas.
The second way to create an array, choose the name for the variable and assign each variable value an index number enclosed in square brackets and assign a value to it. In this case each value is assigned in a spearate statement, and the index numbers must be unique.
Our array assignment would look like:
$vegetable[0] = "beans";
$vegetable[1] = "beets";
$vegetable[2} = "corn";
......etc.
Note: The index numbers as in most if not all programming languages begins with 0 and NOT 1.
Creating an Indexed Array
Getting the Length of An Array: The count() Function
If we want to loop through our arrays and either print the arrays or perform some calculation, having the length of the array will give us the number of times we have to iterate through values.
The PHP count() function does exactly that. The format of the count function is quite simple:
count(the variable name of the array).
Looping Through an Indexed Array
Creating an Associative Array
An associative array the keys have names rather than numbers. What we would have for our example of vegetables if we wanted to create an arry of the cost of each vegetable would be the following.
$ vegetable_cost= array("beets"=> 0.92, "corn" =>0.40, "celery" => 0.63);
or similar to the indexed array, substituting the vegetable name as the key rather than a number:
$vegetable_cost["beets"] = 0.92;
$vegetable_cost["corn"] = 0.40;
$vegetable_cost["celery"] = 0.63;
Creating & Looping Through an Associative Array
Creating a Multidimensional Array
In our original example with vegetables, we created three variable and hence three arrays : one to keep the name of the vegetable, one to record the cost, and a third to keep the stock amount. Although this is an improvement of a variable name for each vegetable, cost, and amount we have a better way of representing this. We can create a multidimensional array.
Thinking in terms of what we would like to store is the vegetable name, cost, and amount we can use a two-dimensional array as follows:
$vegetables = array (
array("beans", 0.40, 18),
array('beets",0.99,8),
array("corn", 0.54, 26),
array celery, 0.65, 100)
);
Essentially, we have created an array $vegetables, which contains four arrays. One does not have to stop at two dimensions. PHP does not have any restriction on the nesting of the arrays, so there could be three, four, five or more arrays. However managing that becomes quite complex. There becomes a better solution for this, using data bases. Which will be covered in future tutorials.
We now turn out attention as to how to manipulate arrays.
Looping Through a multidimensional Array
Were The Examples in This Tutorial Clear?
Wrap Up and What's Next
In this tutorial we looked at the three types of arrays supported in PHP: the indexed, associative, and multi-dimensional array.
The indexed array is quite simple. Integers starting at 0 are used with the variable name to choose the elements to process.
An associative array uses names as the index. Because we are indexing by a name rather than a number we use the foreach statement for the looping construct.
The multi-dimensional array is bet though of as a nesting process, "an array within an array". There is no limit to the number of dimensions of the array however working with more than three dimensions becomes combersome and error prone. There are bettes solutions.
The are a large number of built-in PHP functions to process arrays. Our next tutorial will focus on some of them starting with sorting.