PHP-Loop
<Beginner PHP><Array><Loop><Function><Pre-Def variable><Session><Read Write File><CRUD>
While Loop
execute as long as condition is true
while (condition is true){
code
};
Exemple
$i=1
while ($i<7){ // first check if $i<7 is true - $ = 1 so it is true
echo "value is $i <br />";
$i++; // add + 1 to $i = so make it 2 - and loop
}
//1,2,3,4,5,6
Do while Loop
The condition is tested after executing the statement (TR: yani illa bir kez işlem yapılıyor)
The loop executes at least once
$i=5;
do{
echo"Number is".$i."<br />"; // do not make any check - write directly this
$i++; // then add +1 to $i = make it 2
} while ($i<=7); // $i is now 2 so loop again
//1,2,3,4,5,6,7
For Loop
When you know in advance how many times the script should run
for (init;test;increment){
code
}
init : initialize counter
test: evaluate
- true: continue
- false: end
Note:
if condition is not true it outpiuts nothing
for ($a=0;$a<6;$a++){
echo "value of a: ".$a."<br />;
}
For each Loop
It works only on arrays. It loops through each key/value pair
To output value
foreach(array as $value){
code
}
To output key and value
foreach(array as $key=>value){
code
}
Exemple
$names=array("John","David","Amy");
foreach($names as $name){
echo $name."<br />";
}
Switch and Break Statements
This is alternative = if else if else
Switch (n){
case value 1:
code;
case value 2:
code;
break;
default: // optional
}
Exemple
$today=`Monday`;
switch($today){
case "Monday";
break;
case "Tuesday";
break;
default:
echo "invalid day";
}
Continue statement
Allows skipping over of what remains of the current loop iteration
Exemple
Skip even numbers
for($i=0;$i<10;$i++){
if($i%2==){
continue;
}
echo $i." number,";
}
Skip numbers 10 and 14
for($i=0;$i<=15;$i++){
if ($i==10 || $i==14){ // either x or y is true
continue;
}
echo $i."<br />";
}
Comments
Post a Comment