Thursday, February 3, 2011

For loops-PHP

Assalamualaikum and selamat sejahtera

loops?what it means?well for those who already learn the programming might already know what it is,and for beginner,click here.

make a file named ForLoop.php 
Here the code: 

<?PHP
$counter = 0;
$number = 1;

for($number; $number < 11; $number++
{
$counter = $counter + 1;
print $counter . "<BR>"; 

}
?>

Here a little explanation on this script

for(initial; limit; update){
}

initial
is where you tell PHP the initial value of your loop. In other words, which number to start the loop?So we used this:

$number = 1

Like all variables, you can make up your own name like $iterate,well it all up to you.
You must set or assign the value of $number before the loop begins, like this:

$number = 1
for($number; $number < 11; $number++) {


Or:

for($number = 1; $number < 11; $number++) {

The result is the same – the start number for this loop is 1

Limit

We have to tell PHP when to end your loop or the limit of the loop.So, we’re setting PHP to keep round the loop while the value of the variable $number is Less Than 11.

for($number; $number < 11; $number++) {

When the value of $number is 11 or higher, PHP will stop the loop.

Update

The loops need the update of starting value,in this case,we use $number,so $number need to be add if we set $number=1 or minus if we set $number=10 and the its limit is $number>1.So that,we can update the counter and display its update,thus make us believe the loops is working well.So to update,we usually like this:
  
$number++

the double plus symbol (++) =increment (increase the value by one).
It’s just a short way of saying this:
$number = $number + 1

the double minus symbol(--)=decrement (decrease the value by one)
It’s just a short way of saying this:
$number = $number - 1

So the story of this looping is like this:
“Starting/Initially/$number at a value of 1, keep going round and round while the start/$number value is less than and not equal to 11. Increase the starting/$number value by one each time round the loop.”
  
One more trick

$counter = $counter + 1;
print $counter . "<BR>"; 


or we can use like this:

 $counter++;
 print $counter . "<BR>"; 

 N/NOTE:that's all folk! 

No comments:

Post a Comment