Prev | Current Page 209 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

These
functions are introduced in this section.
Retrieving the Current Array Key
The key() function returns the key located at the current pointer position of input_array.
Its prototype follows:
mixed key(array array)
The following example will output the $capitals array keys by iterating over the
array and moving the pointer:
$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines");
echo "

Can you name the capitals of these states?

";
while($key = key($capitals)) {
printf("%s
", $key);
next($capitals);
}
This returns the following:
Can You name the capitals of these states?
Ohio
Iowa
Note that key() does not advance the pointer with each call. Rather, you use the
next() function, whose sole purpose is to accomplish this task. This function is introduced
later in this section.
Retrieving the Current Array Value
The current() function returns the array value residing at the current pointer position
of the array. Its prototype follows:
mixed current(array array)
140 CHAPTER 5 ?–  ARRAYS
Let??™s revise the previous example, this time retrieving the array values:
$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines");
echo "

Can you name the states belonging to these capitals?

";
while($capital = current($capitals)) {
printf("%s
", $capital);
next($capitals);
}
The output follows:
Can you name the states belonging to these capitals?
Columbus
Des Moines
Retrieving the Current Array Key and Value
The each() function returns the current key/value pair from the array and advances
the pointer one position.


Pages:
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221