PHP Conference Kansai 2025

Voting

: six minus zero?
(Example: nine)

The Note You're Voting On

richard at happymango dot me dot uk
18 years ago
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

<< Back to user notes page

To Top