The for() is a repetitive instruction. It is used when you wish to perform a command, or a block of code several times.
In PHP there are two different types of for loops: for() and foreach().
for (init; condition; increment) { // php instructions }init - is used to set a variable as a counter (but can be any code to be executed once at the beginning of the loop).
<?php for ($i=0; $i<5; $i++) { echo '<br/> The counter is: '. $i; } ?>The first time this loop is run, the $i variable (the counter) is set to the value of 0, ($i=0). Then the condition $i<5 checks to determine whether the code loop should be executed (when the condition is True).
Inside the for instruction you can introduce other "for()" or any conditional statements.
foreach ($array as $value) { // Do something with $value. }The foreach() loop will iterate through every element in $array, assigning the value of each element to the $value variable.
foreach ($array as $key => $val) { // Do something with $key and /or $val. }This construct will place the key and value of the current $array element into their own variables: $key and $val.
<?php $arr = array('n1'=>'one', 'n2'=>'two', 'n3'=>'three'); foreach ($arr as $key => $val) { echo "<br /> The value at $key is $val"; } ?>For every loop iteration, the key and value of the current $arr array element are assigned to $key and $val variables (and the array pointer is moved by one). On the next loop iteration, the "foreach" will be looking at the next array element, and so forth till the last element of the $arr array.
for (init; condition; increment) { if(end_condition) break; // code to be executed }If the end_condition is True, the code after the "break" will not be executed at all, and the execution of "for" loop ends.
<?php for ($i=0; $i<5; $i++) { if ($i==2) break; echo '<br/> The counter is: '. $i; } ?>- Output:
<input type="checkbox" name="a_name" value="value" checked="checked" />
#id { background:url("path_to_image.png"); background-size:contain; background-repeat:no-repeat; }
var rest8_7 = 8 % 7; alert(rest8_7);
$nr = ceil(3.5); echo $nr; // 4