Code Comments
Programming Forum and web based access to our favorite programming groups.Help!
I am using arrays and a while loop for go through all the elements. The
problem is that the first element is missing:
while ($val = next($array))
{
$key = key($array);
echo "$key: $val\n"
}
Post Follow-up to this messageMatthias Braun said the following on 05/06/2005 18:51:
> Help!
>
> I am using arrays and a while loop for go through all the elements. The
> problem is that the first element is missing:
>
> while ($val = next($array))
> {
> $key = key($array);
> echo "$key: $val\n"
>
> }
reset($array);
--
Oli
Post Follow-up to this messageI noticed that Message-ID:
<42a33bbd$0$14739$9b4e6d93@newsread4.arcor-online.net> from Matthias
Braun contained the following:
>
>I am using arrays and a while loop for go through all the elements. The
>problem is that the first element is missing:
>
>while ($val = next($array))
>{
> $key = key($array);
>echo "$key: $val\n"
>
>}
That's what foreach is for
foreach ($array as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
--
Geoff Berrow 0110001001101100010000000110
0011011010110110010001101111011001110010
11
1001100011011011110010111001110101011010
11
Post Follow-up to this messageMatthias Braun wrote:
> Help!
>
> I am using arrays and a while loop for go through all the elements.
> The problem is that the first element is missing:
>
> while ($val = next($array))
> {
> $key = key($array);
> echo "$key: $val\n"
>
> }
next() will always get the next element by moving the pointer ahead. To get
the first element, use current():
$val = current($array);
while ($val !== false) {
$key = key($array);
echo "$key: $val\n";
$val = next($array);
}
Or use list() with each():
while (list($key, $val) = each($array)) {
echo "$key: $val\n";
}
Or even better, use foreach as Geoff mentioned.
JW
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.