00:00
00:00
Newgrounds Background Image Theme

Nue22 just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

Php: Loops 2006-07-20 12:36:29


[PHP: Main]

PHP: Loops

Category: Advanced

Prologue
PHP: Main has a big amount of Tutorials.
Hopefully this one will be a nice add.
I really do also hope that you will understand all the three loops which PHP have and which are explained here.
We'll not go the most advanced part, dealing with break and continue, but I will show you some nice tricks which are quite advanced - so be sure to already know some stuff beforing entering to loops.
You can learn basics from other Tutorials. Check out PHP: Main !

a tip before starting
you can really screw your server and browser for some period if you run a infinite loop.
So, before proceeding, put this before your loop:

<?
set_time_limit(5);
?>

That will exit the script if it runs more than 5 seconds.

while
while loops are known as the easiest loops in PHP.
Unlike their sister loops, do...while, which I will explain later, they keep outputing every time a value is true.

My First While Loop
You must do:
-set up a variable with a number
-set up a expression for while, thus:

while ($int [Comparison Operator] $max)

And while will run as long as $int it is smaler than $max.
Generally.
This can be changed by changing the Comparison Operator.

- in the loop, you must specify a $int++ to avoid infite loop.

<?
$num = 1;
// $max is 10
while ($num <= 10) {
echo "This is a message No. $num. <br /> \n";
$num++;
}
?>

Outputes:
This is a message No. 1.
This is a message No. 2.
This is a message No. 3.
This is a message No. 4.
This is a message No. 5.
This is a message No. 6.
This is a message No. 7.
This is a message No. 8.
This is a message No. 9.
This is a message No. 10.

Easy, huh?

do...while
This actually isn't a stand-alone loop.
It is basically a while loop, but implemented with do 'loop'.
Regular while and do...while loops are same, except for one thing: do...while will, unlike while execute at least once, even if the condition is at beggining false.

do...while syntax

<?
do {

// the actions which run while the loop's condition is true

} while ( condition )
?>

foreach
foreach loops are used for array, only.
With them, you can get all the values from a array. Both indexes and keys.
This loops are similar to implode() function.

Example 1 - my first foreach loop
Situation: we have the content of our fridge put onto a array.
Now we must export that array into a document.

<?
$fridge = array('banana', 'lettuce', 'carrot', 'eggs', 'tomatos', 'milk');
foreach ($fridge as $contents) {
echo "We have $contents. <br /> \n";
}
?>

Output:
We have banana.
We have lettuce.
We have carrot.
We have eggs.
We have tomatos.
We have milk.

Example 2 - getting contents and their index
Situation: same, except that we will now also tell the index of our content.

<?
$fridge = array('banana', 'lettuce', 'carrot', 'eggs', 'tomatos', 'milk');
foreach ($fridge as $indexes => $contents) {
echo "At position $indexes we have $contents. <br /> \n";
}
?>

Output:
At position 0 we have banana.
At position 1 we have lettuce.
At position 2 we have carrot.
At position 3 we have eggs.
At position 4 we have tomatos.
At position 5 we have milk.

'Index' is a position of array's content.
It can be set. If it is not set, it will be a number, the number of that property's position in array.

Example 3 - where / what
Situation: we must output where is something. Like telling a story.
This example will be used so you can better understand indexes.

<?
$a = array('hawaii' => 'nice', 'croatia' => 'hot', 'antartica' => 'cold', 'usa' => 'mild');

foreach ($a as $where => $what) {
echo "In $where is $what. <br /> \n";
}
?>

Outputes:
In hawaii is nice.
In croatia is hot.
In antartica is cold.
In usa is mild.

for
Now I'll scare you!
This words coming from php.net:
for loops are the most complex loops in PHP.

Have enough strength to confront this?
Lets go!

Syntax
The syntax of for is thus:

for ($int; $max; $what)

$int = you initialize a number here. Lets say you set $int to 1.
$max = the number which will be reached, and then the loop will exit. Lets set it to 10.
$what = ++ or --. ++ is increment and -- is decrement. You will almost always set it to ++. We'll set this to ++ now.

Note that I put those variables like so just to explain nicer. $int, $max and $what must have the same variable name (i.e. $i).

So it would go now:
<?
for ($i = 1; $i<=10; $i++) {
echo "My first for loop. <br /> \n";
}
?>

Outputes:
(you would be surprised how a small amount of PHP code can generate big output!)
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.
My first for loop.

Or vica-versa, with decrementing
<?
for ($i=10; $i>=0; $i--) {

echo '$i = ' . $i . '<br /> \n';

}
?>
Outputes:
$i = 10
$i = 9
$i = 8
$i = 7
$i = 6
$i = 5
$i = 4
$i = 3
$i = 2
$i = 1
$i = 0

Something Useful

-outputting random NG BBS Forum with for and next combination.

<?
$a = array('General', 'Where is/How to?', 'Flash', 'Politics', 'Programming', 'Clubs &amp; Crews', 'Audio');
for ($i = 1; $i<=rand(0, count($a)-1); $i++) {
next($a);
}
echo current($a);
?>

You do now realize that for isn't so hard right?
I really thinks it is not.

Buy Buy
-Nino

Response to Php: Loops 2006-07-20 12:59:12


At 7/20/06 12:49 PM, SpamBurger wrote: Good tutorial, but its spelled Outputs not Outputes. Also, you could have explained what => does, and what the next() and current() functions do.

But a example with => is shown, and next() and current() doesn't do much with loops.

Response to Php: Loops 2006-07-20 13:14:22


I see an error with your for() explanation ;) Not onlyy ++ and -- are supported ;) You can do something like this:
for($i = 0; $i <= 10; $i += 2)
echo 'This increments $i by 2!';


"My software never has bugs. It just develops random features. " - Unknown

[ FluxBB developer | Quickmarks 0.5.1 | Strings & Ints - my blog ]

BBS Signature

Response to Php: Loops 2006-07-20 13:20:55


At 7/20/06 01:14 PM, elbekko wrote: I see an error with your for() explanation ;) Not onlyy ++ and -- are supported ;) You can do something like this:
for($i = 0; $i <= 10; $i += 2)
echo 'This increments $i by 2!';

weird, never seen that

Response to Php: Loops 2006-07-20 16:49:26


lol, that's like basic stuff =/


"My software never has bugs. It just develops random features. " - Unknown

[ FluxBB developer | Quickmarks 0.5.1 | Strings & Ints - my blog ]

BBS Signature

Response to Php: Loops 2006-07-20 19:24:51


At 7/20/06 01:20 PM, Nino_JoJ wrote:
At 7/20/06 01:14 PM, elbekko wrote: I see an error with your for() explanation ;) Not onlyy ++ and -- are supported ;) You can do something like this:
for($i = 0; $i <= 10; $i += 2)
echo 'This increments $i by 2!';
weird, never seen that

If you wanted, you could even do something like this:

for($i=0;$hello != bindec('110');$i++){
$hello = 2*$i;
}

Response to Php: Loops 2006-07-20 22:35:36


I saw a syntax error in your do...while explanation.

<?
do {

// the actions which run while the loop's condition is true

} while ( condition )
?>

A do...while loop requires a semi-colon (;) at the end of the conditional statement.


Merkd.com - It Pays to Play

Earn real money by betting and investing; or, sponsor, challenge, compete,

recruit, communicate, network, earn money playing games, and much more.

Response to Php: Loops 2006-07-21 08:05:30


You got a realy bad explanation of the for loop there.
the for loop takes 4 expressions. Here is a better one:
for(exp1;exp2;exp3) exp4;
The first expression will be evaluated when the loop starts
The secound expression will be evaluated before each loop itteration(includeing the first one) and if it returns false the loop will end(and the itteration will not happend). A hint:
try to cache the goal value, since the whoule expression is evaluated each loop itteration.
The third expresion will be evaluated after each loop itteration, but before the secound expression is evaluated(excludeing the first itteration)
The fourth expression is evaluated bethwen the secound and the third. It's usualy the main body of the loop.

You also have an error in the while description, it's not required to use an comparisation.
You can use any expresion that will return true as long the loop should itterate.

Also note that it is valid to use the expression ; where the loop body can go. Watch out for that if you put the braces on a new line, since if you accidently add a ; the loop body is nullified and only executed once.

I will just quickly describe break anbd continue.
Break will end the loop if executed.
Continue will skip to the next expression(adding or the check if the loop continues depending on loop type).
They both need to be ended with a ;

If you are comeing from basic, check out the alternative syntax with :


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.

Response to Php: Loops 2006-07-21 12:08:42


At 7/20/06 07:24 PM, JeremysFilms wrote:
If you wanted, you could even do something like this:

for($i=0;$hello != bindec('110');$i++){
$hello = 2*$i;
}

Ok..but I wanted to show how to use loops. Not how to implement binary language with it...guys do not complicate, I explained how to use loops simply!
We are just confusing others.

At 7/20/06 04:49 PM, elbekko wrote: lol, that's like basic stuff =/

Hm, loops are not so easy. Especially not all.