Showing posts with label Loop statements. Show all posts
Showing posts with label Loop statements. Show all posts

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.

php Loop statements

Loops are used in programming to do the same tasks many times, while a condition is true...
That means, same script will be executed and repeated, until that condition becomes false.

The loop statements used in php are:
while
do ... while
for
foreach

while and do ... while are similar, the only difference is that, the first one will execute the script if and as long as the condition is true, but the second one, will execute the script, then repeat it as long as the condition is true. In brief, when condition is false while will not do the tasks and exit, but do ... while will do them and exit.

For is to repeat tasks a specific number of times, like you want to execute a script 10 times ....

Foreach to repeat tasks for each element in an array.

Next posts will show how to use these statements.

If you have any questions, post them.