note 43952 added to ref.array
| From: | velocd at hotmail dot com | Date: | Fri, 09 Jul 2004 18:53:25 +0000 |
| Subject: | note 43952 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-72932@lists.php.net to get a copy of this message | ||
Iteratively reduce an array to nothing, while advancing the array by first returning the value at
element zero.
-----------------
function reduce(&$array)
{
$size = count($array);
for ($i = 0; $i<$size; $i++)
{
$array[$i] = $array[$i+1];
unset($array[$i+1]);
}
}
function adv(&$array)
{
if (!is_array($array))
return;
$value = $array[0];
unset($array[0]);
reduce($array);
return $value;
}
-----------------
Example
-----------------
$items = array('pizza', 'soda', 'magazine', 'candy bar');
for($i = 0; $i < 4; $i++)
{
echo adv($items);
echo '<pre>';
print_r($items);
echo '</pre>';
}
-----------------
Output
-----------------
pizza
Array
(
[0] => soda
[1] => magazine
[2] => candy bar
)
soda
Array
(
[0] => magazine
[1] => candy bar
)
magazine
Array
(
[0] => candy bar
)
candy bar
Array
(
)
-----------------
Similarly, advance an array without destructing it.
-----------------
function adv($array)
{
static $i = -1;
if (!is_array($array))
return;
return $array[++$i];
}
-----------------
Example
-----------------
$items = array('pizza', 'soda');
for($i = 0; $i < 2; $i++)
{
echo adv($items);
echo '<pre>';
print_r($items);
echo '</pre>';
}
pizza
Array
(
[0] => pizza
[1] => soda
[2] => magazine
[3] => candy bar
)
soda
Array
(
[0] => pizza
[1] => soda
[2] => magazine
[3] => candy bar
)
-----------------
These functions are useful in input forms where you have an array containing the values for the
form, and you need to iterate through the array. In both instances, either function wouldn't
be needed if only the PHP function next() would return the element at 0 on first call, then advance
the pointer to index 1. That wouldn't be pratical for a function of its name, but maybe a new
one.
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43952
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43952&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43952&report=yes
Search -- http://master.php.net/manage/user-notes.php