COM372: Notes, Chapter 3
Using Arrays
pages 79-104
Arrays: An array is a collection of data sharing a common name. Each piece of data is an element of the array. Each element has the name of the array and a system of numbers or names to identify it uniquely (called an index or key). Array elements can contain single numbers or strings (scalar values) or each element can even contain an entire array. Arrays of array elements are called multidimensional arrays. If the array elements are identified by numbers, it is a numerical array; otherwise, if the elements are identified by names, it is an associative array.
As with the individual scalar variables used in chapter 1, arrays have names, types (these can vary within the array), an assignment in computer memory, and values. The main advantages of using arrays are that a single name can be used to refer to a large number of elements, and the elements can be easily manipulated, as follows.
Numerical Indices: Numbered arrays in PHP start with the index zero (0). You can create a simple 3 element array like this: $myarray = array ( 'First Name', 'Last Name', 'Phone Number');. If the array contains an ascending sequence of numbers, use range() function to create the array, as in $myNumbers = range (1,100);. An optional third parameter in range allows you to set the increment between numbers, so that if I wanted only even numbers between 1990 and 2010, I could use $evenYears = range (1990, 2010, 2);. Range can also be used with characters, as $letters = range ('a', 'z');.
To access elements, use the array name and an index, which is written in square brackets [ ]. Remembering that numerical indices start with 0, retrieve the third element in my array of letters with $third_element = $letters [ 2 ];. Replace the value in that element using assignment, as $letters [ 2 ] = 'gamma';.
To access elements in a numerically indexed array, use a for loop, as
for ( $icount=0; $icount<27; $icount++)
echo "letters [ $icount ] ";
Accociate indices: PHP allows you to use any key or index with each element in an array. For example, we could use an array of greek letters that used our letters[] as an index. To fill the array, create it as
$greek_letters = array ( 'alpha'=>letters[0], 'beta'=>letters[1], 'gamma'=>letters[2]...)
When the index is associative, use a foreach loop or list() and each() constructs to access the array's members. You could use the loop like this
foreach ($letters as $outputs);
echo $outputs.
' ';
or
foreach ($letters as $key => $value)
echo $key.'=>'.$value.'<br />';
The each() construct is used with a while loop, as follows (full explanation on page 84):
while( $element = each ( $letters ) )
{
echo $element [ 'key' ];
}
echo ' - ';
echo $element [ ' value ' ];
echo '<br />';
Notice that each() retrieves an element from the array and advances a pointer to the next element in the array each time it is called.
The list() construct is more common than each(). Remembering that we have a non-numerical index and a value for each item in the array, list(), used with each(), can retrieve the index and value as pairs, running through the entire array in a two-line while loop:
while ( list ( $greek, $latin ) = each ($greek_letters) )
echo "$greek - $latin <br /%gt;";
The pointer used with each() must be returned to the first element if you are going to loop through the same array in the same script. You do this with reset, as in reset($greek_letters).
Array Operators: Array operators are similar to their scalar equivalents, but require the arrays to be of the same size (same length or same dimensions for multidimensional arrays). Addition of arrays (matrices) follow the rules of matrix algebra. The operators (page 85) are union (+), equality (==), identity (===), inequality (!= or <>), and non-identity (!==). The union operator, as in $a + $b, adds elements of the second array to the end of the first, but if elements in $b have the same keys as any elements in $a, they will not be added (elements in $a won't be reassigned new values).
Multidimensional Arrays: PHP creates multidimensional arrays be treating each array element as a container for another array. For a two-dimensional array, an extra index is added; the first can be considered an index of rows, and the second an index of columns, or dimensions in X and Y planes. A third dimension (Z) gets a third index, so that $a [0][3][1] could represent a cell in the $a matrix in the first row, fourth column, and second depth level. To access all elements in large matrices, use nested for loops, as
for( $row=0; $row<100; $row++ )
{
for ($col=0; $col<25; $col++ )
}
{
echo '|'.$alphabet_soup [$row][$col};
}
echo '|<br />';
While array manipulation is easier with numerical indices, the listing on page 88 shows use of a numerical row index with an associative column index, the row being accessed with a for loop and the column index names and values with a nested while (list(),each())construct.
Sorting Numerical Arrays: The function sort() sorts and array in ascending values (e.g., sort($greek_letters); values may be numerical or character. Character values are case sensitive, with upper case letters coming before lower case.
When numbers have been entered as text values, those that begin with lower initial values will come first, so that text "12" will come before text "2." Overcome this by passing a constant as a second parameter to sort(); SORT_REGULAR is the default, SORT_NUMERIC translates text into numbers before sorting, and SORT_STRING regards all values as text.
Sorting Associative Arrays: Recall that associative arrays have character-based indices. To sort an associative array by its values, use asort(); to sort it by its indices (=keys), use ksort().
Sorting in Descending Order: Corresponding to sort(), asort(), and ksort(), which sort in ascending order, are the descending sorters, rsort(), arsort(), and krsort().
Sorting Multidimensional Arrays: Pages 91-93 outline development of simple functions to sort multidimensional arrays. In general, these involve an application-specific decision of what to sort first, and then a simple element-by-element sorting algorithm, all written into a callable function; similarly, you can sort in reverse order, again writing your own function (page 93). Built-in usort(), uasort(), and ksort() functions allow you to pair an array with a sorting algorithm, although the utility of this escapes me. More on this in chapter 5.
Shuffling and Reversing Array Order: Occasionally, you may want to randomly select items from a larger set; for instance, you might want to generate 10 practice quiz questions from a list of 200 that you have used over the years, or you might want to select 3 pictures at random to decorate your page, out of a set of 30 that you have listed in a file of jpg images. The function shuffle() randomly reorders the elements in the array, so that you could then choose 10 or 3 and they would be different each time (well, more often than not), as in shuffle($quiz_questions);. The random number generator is seeded and called automatically. The text mentions (page 95) array_rand() but does't define it. W3Schools defines it as "The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key." Syntax is array_rand(array,number), where number specifies how many keys to return.
Array_reverse(), array_push(), and array_pop(): Function array_reverse() produces an array in reverse order; $backwards_alphabet = array_reverse($greek_letters). Array_push() adds an element to the end of an array; array_pop() removes and returns one element.
Filling an array from a text file: If you wrote to a text file using techniques from the previous chapter, you could also read from a text file and, using functions file() and explode() to place into an array separate lines of the text file, or separate delimited (by tabs or commas, for example) data items from teach line. Code is listed on pages 96-98, listings 3.2 and 3.3.
Navigation within an array: The pointer that refers to the current element can be moved using pointer functions (the following all take the array name as an argument).
- current() and pos() are aliases; both return the current element
- next() and each() advance the pointer one element forward; each() returns the current element and then advances the pointer and next() advances the pointer and then returns the element.
- reset() and end() move the pointer to the first and last elements, respectively
- prev() is the opposite of next(), moving to the preceding element and returning the new current element
Array Walking: Function array_walk has three parameters; the first is the array to be affected. The second is the string name of a function that will be applied to each element in the array. The third is an optional user parameter to be passed through to the function. Use of this is illustrated on page 101 in a user-defined function for formatting each element in the array.
Counting elements: Count() and sizeof() count the number of elements in an array. Array_count_values() counts unique values in the array ("set cardinality") and returns an associative array with a frequency table. The unique values from the array will be the keys (indices) for the new array.
Extract(): Function extract() creates a set of scalar variables; the name of each scalar is the key for each array element and the value is the value of the element. A set of parameters (table 3.2, page 103) tells what to do if, for example, there is already a variable with the name of the key (i.e., the new variable "collides" with the existing one).
More online: Additional array functions can be found online at http://www.php.net/array or at the W3Schools PHP tutorial.