Searching...
Monday 8 July 2013

Traversing Arrays


The need to travel across an array (what is an array) and retrieve various keys, values, or both is common, so it’s not a surprise that PHP offers numerous functions suited to this need. Many of these functions do double duty: retrieving the key or value residing at the current pointer location, and moving the pointer to the next appropriate location. These functions are introduced here.

Retrieving the Current Array Key

The key() functions (more about functions in PHP) returns the key located at the current pointer position of the provided 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 "<p>Can you name the capitals of these states?</p>";
while($key = key($capitals)) {
printf("%s <br />", $key);
next($capitals);
}

This returns the following:

Can you name the capitals of these states?
Ohio
Iowa

Note: 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)

Let’s revise the previous example, this time retrieving the array values:

$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines");
echo "<p>Can you name the states belonging to these capitals?</p>";
while($capital = current($capitals)) {
printf("%s <br />", $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. Its prototype follows:

array each(array array)


The returned array consists of four keys, with keys 0 and key containing the key name, and keys 1 and value containing the corresponding data. If the pointer is residing at the end of the array before executing each(), FALSE is returned.

Moving the Array Pointer

Several functions are available for moving the array pointer. These functions are introduced in this section.

Moving the Pointer to the Next Array Position

The next() function returns the array value residing at the position immediately following that of the current array pointer. Its prototype follows:

mixed next(array array)

An example follows:

$fruits = array("apple", "orange", "banana");
$fruit = next($fruits); // returns "orange"
$fruit = next($fruits); // returns "banana"

Moving the Pointer to the Previous Array Position

The prev() function returns the array value residing at the location preceding the current pointer location, or FALSE if the pointer resides at the first position in the array. Its prototype follows:

mixed prev(array array)

Because prev() works in exactly the same fashion as next(), no example is necessary.

Moving the Pointer to the First Array Position


The reset() function serves to set an array pointer back to the beginning of the array. Its prototype follows:

mixed reset(array array)

This function is commonly used when you need to review or manipulate an array multiple times within a script, or when sorting has completed.

Moving the Pointer to the Last Array Position

The end() function moves the pointer to the last position of an array, returning the last element. Its prototype follows:

mixed end(array array)

The following example demonstrates retrieving the first and last array values:

$fruits = array("apple", "orange", "banana");
$fruit = current($fruits); // returns "apple"
$fruit = end($fruits); // returns "banana"

Passing Array Values to a Function

The array_walk() function will pass each element of an array to the user-defined function. This is useful when you need to perform a particular action based on each array element. If you intend to actually modify the array key/value pairs, you’ll need to pass each key/value to the function as a reference. Its prototype follows:

boolean array_walk(array &array, callback function [, mixed userdata])

The user-defined function must take two parameters as input. The first represents the array’s current value, and the second represents the current key. If the optional userdata parameter is present in the call to array_walk(), its value will be passed as a third parameter to the user-defined function.
You are probably scratching your head, wondering how this function could possibly be of any use. Perhaps one of the most effective examples involves the sanity-checking of user-supplied form data. Suppose the user is asked to provide six keywords that he thinks best describe the state in which he lives. A sample form is provided in Listing 5-1.

Listing 5-1. Using an Array in a Form
<form action="submitdata.php" method="post">
<p>
Provide up to six keywords that you believe best describe the state in
which you live:
</p>
<p>Keyword 1:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p>Keyword 2:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p>Keyword 3:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p>Keyword 4:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p>Keyword 5:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p>Keyword 6:<br />
<input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p>
<p><input type="submit" value="Submit!"></p>
</form>

This form information is then sent to some script, referred to as submitdata.php in the form. This script should sanitize user data and then insert it into a database for later review. Using array_walk(), you can easily filter the keywords using a predefined function:

<?php
function sanitize_data(&amp;$value, $key) {
$value = strip_tags($value);
}
array_walk($_POST['keyword'],"sanitize_data");
?>

The result is that each value in the array is run through the strip_tags() function, which results in any HTML and PHP tags being deleted from the value. Of course, additional input checking would be necessary, but this should suffice to illustrate the utility of array_walk().
If you’re working with arrays of arrays, the array_walk_recursive() function (introduced in PHP 5.0) is capable to recursively apply a user-defined function to every element in an array.

0 comments:

Post a Comment

 
Back to top!