Loops
Posted on: July 10, 2009 at 12:00 AM
Advertisement
Loops are the essential part of the program that have instructions to repeat the code itself again and again until certain conditions are met.

3.10. Loops

Loops are the essential part of the program that have instructions to repeat the code itself again and again until certain conditions are met. More than one loops can be used several times in a script.

Loops makes easy to write the program, saves times and shorten the scripting. It instruct the codes to repeat again and again until the result found or the number of times instructed for repetition of the code.

PHP Loops

In PHP, like other programming language, it has following looping statements:

  • While Loop
  • Do..While
  • For Loop
  • Foreach Loop

3.10.1. While Loop

While loops are usually used for incrementing and decrementing a variable until the repetitions are met to a maximum or minimum value that you've set. The while loop says,

while (something is true)

{

// do something that you specify

}

Using While loop we can print the counting from 1 to n- numbers. Here N refers to limit from which the code will run.

a. the variable $Counting = 1;

b. print $ Counting;

c. add 1 to $ Counting;

d. go to sep a. and run this script again with the new value of $ Counting;

d. stop when $MyNumber reaches 11;

The syntax for incrementing and decrementing the value of a variable is:

$a++;

adds 1 to the value of the variable $a each time through

$a--;

subtracts 1 from the value of the variable $a each time through

So the code itself for printing the numbers 1 to 10 may look like this:

<?php

$Counting = 1;

while ($Counting <= 10)

{

print ("$Counting");

$ Counting++;

}

?>

  • start PHP code;
  • set variable $ Counting to 1;
  • initiate ?while? loop: while the variable $Counting is less than or equal to 10, execute what's below; otherwise move on;
  • print the current value of $Counting;
  • add 1 to the value of $Counting;
  • end PHP code.
Advertisement

Related Tags for Loops:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 10, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com