For Loops in PHP

(0 votes, average 0 out of 5)

To create a for loop in php, follow these simple steps:

  1. Set a counter variable to some initial value.
  2. Check to see if the conditional statement is true.
  3. Execute the code within the loop.
  4. Increment a counter at the end of each iteration through the loop.

The following is pseudo php code for a for loop:

1
2
3
for(init counter; conditional statement; increment counter){
	inner code;
}

As you can see, all of the above steps are taken care of within the for loop, making the syntax short and easy to understand. 

Here is an example of a php for loop:

1
2
3
4
5
6
7
8
9
10
11
$price = 5;
 
echo "\"0\">";echo "";echo "";for( $count = 0; $count <= 10; $count++){	echo "";	echo "";}echo "
Quantity Total Price
".$count." ".$price * $count."
"
;

The code above will produce the following output:

Quantity Total Price
0 0
1 5
2 10
3 15
4 20
5 25
6 30
7 35
8 40
9 45
10 50

 

 

 

 

 

 

 

 

 

 

 

Partner Links:
Last Updated on Tuesday, 29 June 2010 07:32  
Related Articles

» PHP - Check if a string contains a substring

In many object-oriented languages, you often want to check for the presence of a substring in a string. PHP does not contain a .contains() method which you can use, but you can create your own using the function quite easily:12345678910111213141516171819/*** Checks to see of a string contains a particular substring* @param $substring the substring to match* @param $string the string to search * @return true if $substring is found in $string, false otherwise*/function contains($substring,...

» How to Break Out of a for/while Loop in Perl

Loop control in Perl is very easy, like most languages, but the syntax does differ slightly from what a lot of languages use.  There are a number of ways to control execution inside of a loop but the two most common are next and last.next: Begins the next iteration of the loop without executing anything that follows. (The C analogy to this is continue -- be careful because continue has a completely different effect in perl).last:   End execution of the loop immediately.There are...

» Resolve Input/Output error when trying to write to WebDAV (davfs2) mount like box.net on Linux

These instructions assume that you already configured the WebDAV filesystem by following .If you are mounting a WebDAV folder on Linux using the davfs2 FUSE filesystem, you may encounter the following error when trying to write a file to the WebDAV filesystem:cp: cannot create regular file `test.txt': Input/output errorThis is caused by the WebDAV filesystem not supporting file locks. The solution is to disable file locks in the davfs2 configuration file, located...