Array Manipulation With PHP4 - Where Am I?
(Page 6 of 8 )
A number of built-in functions are available for use while iterating through an array - you'll typically use these in combination with a "while" or "for" loop.
The current() function returns the currently-in-use element of an array (beginning with the first element),
<?
// create array
$friends = array("Rachel", "Monica", "Phoebe", "Joey", "Chandler", "Ross");
// returns "Rachel"
echo current($friends);
?>
while the key() function returns the corresponding array key.
<?
// create array
$friends = array("Rachel", "Monica", "Phoebe", "Joey", "Chandler", "Ross");
// returns "Rachel"
echo current($friends);
// returns 0
echo key($friends);
?>
The next() and prev() functions move forward and backward
through the array.
<?
// create array
$friends = array("Rachel", "Monica", "Phoebe", "Joey", "Chandler", "Ross");
// returns "Rachel"
echo current($friends);
// move forward
next($friends);
// returns "Monica"
echo current($friends);
// move forward
next($friends);
// returns "Phoebe"
echo current($friends);
// move backwards
prev($friends);
// returns "Monica"
echo current($friends);
?>
The reset() and end() functions move to the beginning and end
of an array respectively,
<?
// create array
$friends = array("Rachel", "Monica", "Phoebe", "Joey", "Chandler", "Ross");
// returns "Rachel"
echo current($friends);
// move to end
end($friends);
// returns "Ross"
echo current($friends);
// move forward
reset($friends);
// returns "Rachel"
echo current($friends);
?>
while the each() function comes in handy when you need to
iterate through an array.
<?
// create array
$music = array("pop", "rock", "jazz", "blues");
// creates the array ("0" => 0, "1" => "pop", "key" => 0, "value" => "pop")
$this = each($music);
// returns "0" - no key, as this is not a hash
echo $this["0"];
// returns "pop"
echo $this["1"];
// returns "0" - no key, as this is not a hash
echo $this["key"];
// returns "pop"
echo $this["value"];
?>
Confused? Don't be - every time each() runs on an array, it
creates a hash containing four keys: "0", "1", "key" and "value". The "0" and "key" keys contain the name of the currently-in-use key of the array (or hold the value 0 if the array does not contain keys), while the "1" and "value" keys contain the corresponding value.
Here's another example to make this clearer:
<?
// create array
$music = array("pop" => "Britney Spears", "rock" => "Aerosmith", "jazz" =>
"Louis Armstrong");
// creates the array ("0" => "pop", "1" => "Britney Spears", "key" =>
"pop", "value" => "Britney Spears")
$this = each($music);
// returns "pop"
echo $this["0"];
// returns "Britney Spears"
echo $this["1"];
// returns "pop"
echo $this["key"];
// returns "Britney Spears"
echo $this["value"];
// move forward
// creates the array ("0" => "rock", "1" => "Aerosmith", "key" => "rock",
"value" => "Aerosmith")
$this = each($music);
?>
Next: Sorting Things Out >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire