note 74463 added to function.array-shift

From: Date: Thu, 12 Apr 2007 13:09:39 +0000
Subject: note 74463 added to function.array-shift
Groups: php.notes 
Request: Send a blank email to php-notes+get-125337@lists.php.net to get a copy of this message
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this. <?php while($key = key($array)) { $value = array_shift($array); //code goes here } ?> its like foreach but each time the value is removed from the array so it eventually ends up empty <?php //example below $airports = array ( "LGW" => "London Gatwick", "LHR" => "London Heathrow", "STN" => "London Stanstead" ); echo count($airports)." Airport in the array<br /><br />"; while($key = key($airports)) { $value = array_shift($airports); echo $key." is ".$value."<br />"; } echo "<br />".count($airports)." Airport left in the array"; ?> Example Outputs: 3 Airport in the array LGW is London Gatwick LHR is London Heathrow STN is London Stanstead 0 Airport left in the array ---- Server IP: 194.145.210.4 Probable Submitter: 80.194.36.8 ---- Manual Page -- http://www.php.net/manual/en/function.array-shift.php Edit -- https://master.php.net/note/edit/74463 Del: integrated -- https://master.php.net/note/delete/74463/integrated Del: useless -- https://master.php.net/note/delete/74463/useless Del: bad code -- https://master.php.net/note/delete/74463/bad+code Del: spam -- https://master.php.net/note/delete/74463/spam Del: non-english -- https://master.php.net/note/delete/74463/non-english Del: in docs -- https://master.php.net/note/delete/74463/in+docs Del: other reasons-- https://master.php.net/note/delete/74463 Reject -- https://master.php.net/note/reject/74463 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#125337) next »