LOOPS IN PHP:

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

Break Statement

Break ends execution of the current for, foreach, while, do..while or switch structure. Break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

PHP Example:-

<?php
echo "<p><b>Example of using the Break statement:</b></p>";
for ($i=0; $i<=10; $i++)
 {
   if ($i==3)
   {
     break;
   }
   echo "The number is ".$i;
   echo "<br />";
 }
?>

Continue Statement

Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.

Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

PHP Example:-

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";
for ($i=0; $i<=10; $i++)
 {
   if ($i==3)
   {
     continue;
   }
   echo "The number is ".$i;
   echo "<br />";
 }
?> 

Do.. While Statement

Do..while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do..while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

Syntax:-

do {
// code to be executed
} while ( expression );

PHP Example:- The code block is executed a minimum of one time.

<?php
$num = 1;
do {
 echo"Execution number: $num<br>\n";
 $num++;
} while ( $num > 200 && $num < 400 );
?>

The do...while statement tests whether the variable $num contains a value that is greater than 200 and less than 400. In line 7, we have initialized $num to 1, so this expression returns false. Nonetheless, the code block is executed before the expression is evaluated, so the statement will print a single line to the browser.

For Statement

For loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:.

Syntax:-

for ( initialization expr1; test expr2; modification expr3 )
{ // code to be executed }

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

PHP Example:- All of them display numbers from 1 to 10:

<?php
for ($i = 1; $i <= 10; $i++) {
    echo "$i\n";
}
for ($i = 1; ; $i++) {
  if ($i > 10) {
      break;
  }
  echo "$i\n";
 }
?>

Foreach Statement

PHP 4 (not PHP 3) includes a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

Syntax:-

foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

While Statement

While loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

Syntax:-

while ( expression ) {
// do something }

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

PHP Example: The following code are identical, and both print numbers from 1 to 10:

<?php
$i = 1;
while ($i <= 10) {
echo "$i\n";  
$i++;
}

Try

Try

Try

Try

Assignment Try

Write a PHP program to find the percentage of a student for input given in following manner
3
rag 78 56 72
teja 83 67 78
bhavana 83 75 67
bhavana
output- 75

Input
enter number of students:4
enter the details of students-
bhavana 45 89 98
rag 56 89 74
teja 78 89 99
niha 96 66 85
Enter student for percentage:rag

Output
percentage of rag is 73

<?
$msg="enter number of students:";
echo $msg;
//takes the value of number of students
$n=trim(fgets(STDIN, 1024));
echo "enter the details of students:\n";
//loop continues till the number of students given
//name and values are take in the form of string and then converts in to array using explode function
for($i=0;$i<$n;$i++)
{
  $q=trim(fgets(STDIN, 1024));
  $q=explode(" ",$q);
  //the complete marks is taken in to an other marks
  $marks[$i]=$q;
}
echo "Enter student for percentage:";
//takes input of the person to know the marks
$st=trim(fgets(STDIN, 1024));
//verifies all the names that are present in the marks of marks first index
for($i=0;$i<$n;$i++)
{
 if($st==$marks[$i][0])
 {
  //calculates the percentage of the person
  $sum=($marks[$i][1]+$marks[$i][2]+$marks[$i][3])/3;
  echo "percentage of $st is $sum\n";
  break;
 }
}
?>

Assignment Try

Write a PHP program to print the name of student having second least percentage from the given list of students , if there are multiple students should print multiple students in alphabetical order
Input-
5
rag
77
teja
89
bhavana
84
praveen
77
bhadram
75

Output-
praveen
rag

Input
enter number of students:4
enter student details-
bhavana
96
rag
89
teja
89
niha
45

Output
students with second least marks-
rag
teja

<?
$msg= "enter number of students:";
echo $msg;
//takes the value of number of students
$stud=trim(fgets(STDIN, 1024));
$msg="enter student details:";
echo $msg;
//initializes the multidimensional array with student names and marks respectively
for($i=0;$i<$stud;$i++)
{
  $marks[$i][0]=trim(fgets(STDIN, 1024));
  $marks[$i][1]=trim(fgets(STDIN, 1024));
}
//to sort the marks of the students along with their names
for ($i = 0; $i < $stud; ++$i)
 {
  for ($j = $i + 1; $j < $stud; ++$j)
   {
    if ($marks[$i][1] > $marks[$j][1])
     {
      $a =  $marks[$i][1];
      $marks[$i][1] = $marks[$j][1];
      $marks[$j][1] = $a;              
      $a =  $marks[$i][0];
      $marks[$i][0] = $marks[$j][0];
      $marks[$j][0] = $a;
     }
   }
 }
$i=0;
//to leave the least marks as we want to display the second least
while($marks[$i][1]==$marks[$i+1][1])
{
  $i++;
}
$j=$i+1;
$k=0;
//stores the first name of second least
$names[$k]=$marks[$j][0];
//to store all the second least marks student names
while($marks[$j][1]==$marks[$j+1][1])
{
  $k++;
  $names[$k]=$marks[$j+1][0];
  $j++;
}
//sort the names according to alphabet
sort($names);
$s=count($names);
echo "students with second least marks:\n";
//displays the names of the students
for($i=0;$i<$s;$i++)
{
  echo $names[$i]."\n";
}
?>

Assignment Try

Write a PHP program to use array as set in the code to store only unique items in a array or list manner

Input
enter list of your choice with repetition:12 54 12 54 78 78 79

Output
Array
(
[0] => 12
[1] => 54
[4] => 78
[6] => 79
)

<?
//the message that is to be displayed is stored in msg variable
$msg = "enter list of your choice with repetition:";
//echo displays the message
echo $msg;
//STDIN takes the input from the user
$a = fgets(STDIN, 1024);
//trin function avoids the whitespaces from the user input
$a = trim($a);
//explode function splits the numbers in to array
$b = explode(" ",$a);
//array_unique function takes the unique elements from the array
$c = array_unique($b);
//print_r functions prints the entire array
print_r($c);
?>