Page 137 - Open Soource Technologies 304.indd
P. 137
Unit 6: Arrays
The preceding code uses the each() function, which we have not used before. This function Notes
returns the current element in an array and makes the next element the current one. Because
we are calling each() within a while loop, it returns every element in the array in turn and stops
when the end of the array is reached.
In this code, the variable $element is an array. When we call each(), it gives us an array with
four values and the four indexes to the array locations. The locations key and 0 contain the key
of the current element, and the locations value and 1 contain the value of the current element.
Although it makes no difference which you choose, we have chosen to use the named locations,
rather than the numbered ones.
There is a more elegant and more common way of doing the same thing. The function list ()
can be used to split an array into a number of values. We can separate two of the values that
the each() function gives us like this:
$list ( $product, $price ) = each( $prices );
This line uses each() to take the current element from $prices, return it as an array, and make
the next element current. It also uses list() to turn the 0 and 1 elements from the array returned
by each() into two new variables called $product and $price.
We can loop through the entire $prices array, echoing the contents using this short script.
while ( list( $product, $price ) = each( $prices ) )
echo “$product - $price<br />”;
This has the same output as the previous script, but is easier to read because list() allows us to
assign names to the variables.
One thing to note when using each () is that the array keeps track of the current element. If we
want to use the array twice in the same script, we need to set the current element back to the
start of the array using the function reset (). To loop through the prices array again, we type
the following:
reset($prices);
while ( list( $product, $price ) = each( $prices ) )
echo “$product - $price<br />”;
6.1.2 Indexed Arrays
Arrays can most easily be described as an ordered list of elements. You can access the individual
elements by referring to their index position within the array. The position is either specified
numerically or by name. An array with a numeric index is commonly called an indexed array
while one that has named positions is called an associative array. In PHP, all arrays are associative,
but you can still use a numeric index to access them.
Example of an indexed Array:
<?php
$seven = 7;
$arrayname = array( “this is an element”, 5, $seven );
echo $arrayname[0]; //prints: this is an element
echo $arrayname[1]; //prints: 5
echo $arrayname[2]; //prints: 7
?>
LOVELY PROFESSIONAL UNIVERSITY 131