Skip to content
WJunction - Webmaster Forum

PHP Tutorial (Loopy Loops) Basics

Status
Not open for further replies.
Heya all,

Here is a tutorial regarding Loops and i hope you can understand it, if you have any questions regarding this tutorial please post

PHP:
<?php

/*
	Heres the php tutorial on LOOPS, there are several types of loops and each loop can pretty
	much acomplish the same outcome but theres some better than others so here are the types of
	loops.
|---
	Name: for loop
	Usage: Maily used for looping intergers
	Example:
	for(condition){
		
	}
|---
	Name: foreach loop
	Usage: Mainly used to loop threw array
	Example:
	foreach(array as variable){
		
	}
|---
	Name: while loop
	Usage: continue until condition is not true
	Example:
	while(condition){
	
	}
	
	Ok so in order ill show you some examples below
*/

/*------------------ForLoop------------------*/

	for ($i=0; $i < 10;$i++) {
		echo $i;
	}
//Output would be | 012345678910

	for ($i=10 $i > 0; $i--){
		echo $i;
	}
//Output would be | 109876543210

/*----------------ForeachLoop----------------*/
$simple_array = array(1,2,3,4,5,"Litewarez",7,8,9,10);
foreach($simple_array as $array_item){
	echo $array_item . "<br />"
}
//Output would be | 1<br />2<br />3<br />4<br />5<br />Litewarez<br />7<br />8<br />9<br />10<br />
$assoc_array = array(1 => "one",2 => "two",3 => "three",4 => "four",5 => "five",6 => "six",);
foreach($assoc_array as $assoc_name => $assoc_value){
	echo "INT:" . $assoc_name . " = " . $assoc_value . "<br />";
}
/*
	Html Output:
	
	INT: 1 = one
	INT: 2 = two
	INT: 3 = three
	INT: 4 = four
	INT: 5 = five
	INT: 6 = six
*/

/*----------------WhileLoop----------------*/

//While loops are most commenly used to loop threw a mysql 
//resource so that is the example ill show below.

//Usume Connected to MySql

$resource = mysql_query("SELECT int,word FROM numbers LIMIT 6");

while($row = mysql_fetch_assoc($resource)){
	echo "INT:" . $row['int'] . " = " . $row['word'] . "<br />";
}

/*
	Html Output:
	
	INT: 1 = one
	INT: 2 = two
	INT: 3 = three
	INT: 4 = four
	INT: 5 = five
	INT: 6 = six
*/

/*
	theres one more example that i want to show you where you take the contidtion
	and use a predefined constant such as true to make the loop never ending untill the
	break; 
*/

while (true){
	$row = mysql_fetch_assoc($resource); 
    if (!$row){
		break; // this will exit the while loop
	}
	echo "INT:" . $row['int'] . " = " . $row['word'] . "<br />";
}

?>

Also if you want to understand any aspects of php please just ask below and ill do my best to explain and show examples:¬)
 
Status
Not open for further replies.

About the author

L
Active Member · Joined
I am a skilled programmer within PHP,HTML,CSS,MYSQL and also the owner of several websites Programming, Football...
1,367
Messages
1
Reactions
38
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom