php Loop - what is loop in php?
a loop is a sequence of instructions that is continually repeated until a certain condition is reached.
There are various type of loop statements in PHP.
while loop
do..while loop
for loop
foreach loop
while loop :
while statement has three part of its structure. That is, initialization, conditional expression and statement to handle increments or decrements. This is shown as follows.
initialization
while(condition) {
//set of expressions to be execute recursively
...
increment (or) decrement
}
File name : index.php
$i=1;
while($i <= 3) {
echo $i;
$i++;
}
?>
Output :-
do while loop
initialization
do {
//set of expressions to be execute recursively
...
increment (or) decrement
}while(condition)
File name : index.php
$i = 1;
do {
echo $i;
$i++;
} while (($i > 1) && ($i <= 3)); ?>
Output :-
for loop
for loop structure will facilitate the developer for easy understanding of code flow. Because, it holds all parts of a loop statement, that is, initialization, condition and increments/decrements part in one single statement. The syntax of for loop structure is as shown as below.
syntax
for(initialization; conditional statement; increments (or) decrements) {
//set of expressions to be execute recursively
}
File name : index.php
for($i=1;$i <= 3;$i++) {
echo $i;
}
?>
Output :-
foreach loop
foreach is used to organize an array with the key,value pair.
File name : index.php
foreach($array as $value_array) {}
(or)
foreach($array as $key_array=>$value_array) {}
foreach example :
File name : index.php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
echo $value;
}
foreach example 2:
File name : index.php
$i=0;
$data_array = array();
$arr = array();
foreach ($arr as &$row) {
$data_array[$i]['id'] = $row[0]['id'];
$data_array[$i]['name'] = $row[0]['name'];
$data_array[$i]['address'] = $row[0]['address'];
$data_array[$i]['pincode'] = $row[0]['pincode'];
$i++;
}
Output :-
example
File name : index.php
$name = array("Sara", "Arham", "Sana", "Kashaf");
foreach ($name as $value) {
echo "$value
";
}
?>
Output :-
foreach example
File name : index.php
$input_array = array("Kashaf","Arham","Sana");
foreach($input_array as $value) {
$caps_value_array[] = ucfirst($value);
}
print "
Getting Array Values";
print "
";
print_r($caps_value_array);
print "
";
?>
Output :-
Getting Array Values
Array
(
[0] => Kashaf
[1] => Arham
[2] => Sana
)
example
File name : index.php
$input_assoc_array = array("fruit1"=>"apple","fruit2"=>"orange","fruit3"=>"grapes");
foreach($input_assoc_array as $key=>$value) {
$caps_assoc_array[$key] = ucfirst($value);
}
print "
Getting Array Values";
print "
";
print_r($caps_assoc_array);
print "
";
Output :-
Getting Array Values
Array
(
[fruit1] => Apple
[fruit2] => Orange
[fruit3] => Grapes
)
Previous
Next