views:

258

answers:

2

How can you convert foreach -statements to for -loops in PHP?

Examples to be used in your answers

1

 foreach( $end_array[1]['tags'] as $tag )

and

2

 foreach($end_array as $question_id => $row2)
+3  A: 

In both examples the expressions left to 'as' refer to an array. An array stores a mapping of keys to values. Both examples iterate through elements of this mapping.

In the first example you are only interested in the values (and not in the keys they are mapped to). At every iteration $tag refers to the "current" value.

In the second example $question_id refers to the key, $row2 refers to the value of the "current" mapping.

In general the expression

foreach($array as $key => $value) {
  ...
}

could be rewritten as

$keys = array_keys($array);
for($k=0; $k < count($keys); $k++) {
  $key = $keys[$k];
  $value = $array[$key];
  ...
}
Zed
A: 

The converted for code has syntax problems, try the following (which also works faster for huge arrays):

$keys = array_keys($array);
for ($k = 0, $key_size = count($keys); $k < $key_size; $k++) {
  $key = $keys[$k];
  $value = $array[$key];
  ...
}
BlueMM