May 12, 2007 4:13:34 GMT -5
Hello,
PHP knows several loop functions:
- For-loop
- While-loop
- Foreach-loop
I'll try and explain them as good asd I can for you
For-loopThe for loop loops untill a variabel reaches the number you tell it to.
Code:
for( expr1; expr2; expr3 )
{
statement
}
expr1 contains the var (and wich number it currently is). Let's say we name it $i with the number 1.
expr2 will look if it has to stop. Let's say we want to count to 10. So we do $i <= 10.
expr3 will run if expr2 returns false. Now we want to add 1 to $i so we do $i++. This becomes:
Code:
for( $i = 1; $i <= 10; $i++ )
{
statement
}
Now where it says statement, you add the code wich has to be run. Let's just make it say the number:
Code:
for( $i = 1; $i <= 10; $i++ )
{
echo $i . "<br />\n";
}
Now it will count from 1 to 10!
While-loopThe while loop keeps on running untill the expression returns false. This can be used for MySQL functions, such as mysql_fetch_array & assoc, but also for looping untill a variable changes.
Code:
while( expr )
{
statement
}
expr can be multiple things. In this tut I'll check if $name contains false; So we replace expr with $name == false
Now it will run untill $name is containing false. First we have to assign the var (with false):
Code:
<?php
$name = false;
while($name == false )
{
statement
}
Now, you can't just run this. This will run forever! First you have to change $name SOMEWHERE between the brackets. I'll make an example code:
Code:
<?php
$name = false;
$num = 0;
while($name == false )
{
if( $num != 5 )
{
echo $num . "<br />\n";
} else {
$name = true;
}
$num++;
}
Now it will output:
0
1
2
3
4
5
And then stop.
Foreach-loopThe foreach loop goes through all keys (and values) from an array.
Code:
foreach( array_expression as $value )
statement
and
Code:
foreach( array_expression as $key => $value )
statement
The first one only grabs the values of an array, and the second one grabs both the key and value.
array_expression must be replaced with the array.
$value will return the value.
$key will return the key.
Both $value and $key can have any name.
Let's make an example:
Code:
<?php
$arr = array(
"foo" => "bar",
"name" => "xikeon"
);
foreach( $arr as $key => $value )
{
echo $key . ": " . $value . "<br />\n";
}
?>
This will output:
foo: bar
name: xikeon
Nothing more to say I guess..
Hope it helps, have fun
Greetings,
Mike.