The for loop has the following formal definition:
for ([counter initialization]; [condition]; [counter change]) { // actions }
example for loop:
for ($i = 1; $i < 10; $i++) { echo $i; }
Parts of the for loop declaration may be missing. For example, there is no counter definition (it can be defined outside the loop):
$m = 5; for (; $m < 10; $m++) { echo $m; }
Changing the counter value and change it inside the loop:
$i = 0; for (; $i < 10;) { echo $i; $i += 2; }
Also, you can define and use several variables in the loop declaration at once:
for ($i =1, $m=1; $i + $m < 100; $i++, $j+=10) { echo "$i + $m = " . $i + $m "; }
alternative syntax:
for ($i = 1; $i < 10; $i++): echo $i * $i"; endfor;
Iterating the array using the for loop
//create array $array[] = '1'; $array[] = '2'; $array[] = '3'; //count array length $count = count($array); //pass the array for ($i=0; $i<$count; $i++) { echo $array[$i]; }
Pass associative array using the for loop
reset() – sets the pointer to the first element of the array;
next() – moves the pointer forward one element of the array;
key() – returns the key of the current array element.
$array['One'] = 1; $array['Two'] = 2; $array['Three'] = 3; for (reset($array); ($key = key($array)); next($array)) { echo $key. '=>' .$array[$key] . '<br>'; }