This was posted on 02/08/2011 and was filed in Guides and Information, PHP, Code Snippets | (No Comments Yet)
I receive a LOT of questions about loops and how/when to use them. Hopefully this will answer a few of the basic questions. I'll add more to this as more questions come in.
Always be careful with loops and the syntax you use with them. Unterminated or long-lasting loops can cause pages to take long periods of time to load and can even crash servers. Normally, if you have a never-ending loop your PHP.ini settings (max_execution_time) will stop the loop before it executes for too long. By default, this value is set at 30 seconds.
FOR LOOP
When Do We Use It?
Want to count to a certain number from a certain number. This is good for showing a certain number of objects or looping through simple arrays.
For Loop Example
For example, I want to show 10 input boxes for a client I can use the following code:
{
echo 'Something '.$boxCount.': <input type="text" name="boxes[]" id="box-'.$boxCount.'" /><br/>';
}
OUTPUT:
Something 1:
Something 2:
Something 3:
Something 4:
Something 5:
Something 6:
Something 7:
Something 8:
Something 9:
Something 10:
FOREACH
When Do We Use It?
When we want to go through a complex array with no standardized KEY.
For Each Loop Example
foreach ( $myArray as $KEY => $VALUE ) {
echo '<b>'.$KEY.':</b> '.$VALUE.'<br/>';
}
OUTPUT:
Something: Else
1: Another
2: 3453
3: 234
4: Hello!
WHILE LOOP
When Do We Use It?
When we want to loop through until a number has hit a certain point or a variable returns false. Commonly used with mysql queries.
While Loop Examples
while ( $x != 40 )
{
$x++;
}
echo $x;
OUTPUT:
$numberFound = false;
$guessNumber = 0;
while ( !$numberFound ) // While NOT Number Found - While loops must remain TRUE to run.
{
if ( $guessNumber == $randomNumber ) $numberFound = true;
else $guessNumber++;
}
echo 'The number was: '.$guessNumber;
OUTPUT:
Have I Helped You? Share Some Love!
Comments
» No Comments have been made on this. How about you start us off?
Comment On This
Browse By Category
- All Posts
- Useful Websites
- Money Savers
- Tips And Tricks
- Social Media
- Guides and Information
- PHP
- How-Tos
Latest Posts
- » PHP Unserializer
- » How To: Quickly Add a New PHP Extension Via SSH
- » Easily Open A TCP Port On Your Stock cPanel Server
- » Free Code: Find The Total Line Count Of A Folder Using PHP
- » Free Code: ReCaptcha Form Validation With PHP
- » View All
Advertising
© Max Morgan Design 2009 - 2012 | Page Generated In 0.18573 Seconds Using 42 MYSQL Queries


