foreach ($a as $b)
{
do function
}
views:
151answers:
3
+1
A:
$i = 0;
while ($i < count($a))
{
$b = $a[$i];
//do function
$i++;
}
luvieere
2009-11-06 21:23:15
Good, but the count might not be available for all enumerations.
uosɐſ
2009-11-06 21:24:46
also, this assumes that keys are integers from 0 to the count - 1, which is not necessarily the case
newacct
2009-11-06 21:29:09
It would also be more efficient to place the count() outside of the loop to prevent recounting the array every single time.
BraedenP
2009-11-06 21:31:02
The count() is only executed once, that's how the while loop works.
luvieere
2009-11-06 21:41:47
@luvieere: a while loop executes its test at the beginning of each iteration through the loop. In your example, `count($a)` will be executed multiple times. If you want to test this, try `function mycount($a) { echo 'test'; return count($a); }` and then `while ($i < mycount($a))`
gnarf
2009-11-07 20:29:52
+5
A:
reset($a);
while (list($key, $value) = each($a)) {
//...
}
$keys = array_keys($a);
while (($key = array_shift($keys)) !== NULL))
{
$b = $a[$key];
}
gnarf
2009-11-06 21:30:37