For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > June 2005 > While loop in array does not start with first entry









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author While loop in array does not start with first entry
Matthias Braun

2005-06-05, 3:56 pm

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"

}
Oli Filth

2005-06-05, 3:56 pm

Matthias 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
Geoff Berrow

2005-06-05, 8:55 pm

I 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
Janwillem Borleffs

2005-06-05, 8:55 pm

Matthias 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



Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com