PHP For Loop

When you need to do the same script many times, for exemple you want to send emails to all your users, you don't need to write a php code for each user, you just need to use for Loop which will do it for each one.
This is how:
<?php
for ($userid=1;$userid<=10;$userid++){
send_email($userid);
}
?>

Where send_email() is your own function that send the email to the user with the id as parameter.

Another exemple to For Loop, let's say you want to count 1+2x2+3x3+...+nxn, this is how you can do it:
<?php
$n=10;
$t=0;
for ($i=1;$i<=$n;$i++){
$t+=$i*$i; // the same as $t=$t+$i*$i
}
?>


So how For loop works ?

1. Set a counter variable to some initial value (i.e $i=0).
2. Check to see if the conditional statement is true(i.e $i<=10).
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop(i.e $i++, or $i+=1, ou $i=$i+1) .

And this is how to do it:
for ( initialize a counter; conditional statement; increment a counter){
do this code;
}


The php loop will help you a lot in php programming, and there are other ways to do loops other that For, like while.

3 comments:

Custom-Web-design said...

Great work...if you can give another example then it would be more easy to understand.

Cegonsoft said...

It's a nice example..

Jack said...

Quite worthwhile info, thank you for the article.
sex in office | cast aluminum | Toronto condos