note 43950 deleted from ref.array by nlopess

From: Date: Fri, 09 Jul 2004 18:56:18 +0000
Subject: note 43950 deleted from ref.array by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72934@lists.php.net to get a copy of this message
Note Submitter: velocd@hotmail.com ---- 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.

« previous php.notes (#72934) next »