note 75069 added to function.each

From: Date: Thu, 10 May 2007 19:36:44 +0000
Subject: note 75069 added to function.each
Groups: php.notes 
Request: Send a blank email to php-notes+get-126395@lists.php.net to get a copy of this message
If you want to iterate over a two-dimensional, sparse array, and want to first display every first element, then every second and so on, you can use this code: $fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third", 10 => "fourth", ) ); $done = False; while ($done == False) { $done = True; // Important: &$val has to be a reference (use the &), // if you don't, the internal counter of $val will be // re-initialized each time and you loop over the first elements // for eternity. foreach($fruits as $key => &$val) { if (list($inner_key, $inner_val) = each(&$val)) { $done = False; echo "$key : : $inner_key => $inner_val <br> \n"; } } } NOTE: this is just a quick hack, if you know a better way, post it! ---- Server IP: 69.147.83.197 Probable Submitter: 85.2.234.188 ---- Manual Page -- http://www.php.net/manual/en/function.each.php Edit -- https://master.php.net/note/edit/75069 Del: integrated -- https://master.php.net/note/delete/75069/integrated Del: useless -- https://master.php.net/note/delete/75069/useless Del: bad code -- https://master.php.net/note/delete/75069/bad+code Del: spam -- https://master.php.net/note/delete/75069/spam Del: non-english -- https://master.php.net/note/delete/75069/non-english Del: in docs -- https://master.php.net/note/delete/75069/in+docs Del: other reasons-- https://master.php.net/note/delete/75069 Reject -- https://master.php.net/note/reject/75069 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#126395) next »