Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 69
Comments: 20 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
Using Loops in PHP
Using loops in conjunction with arrays is an excellent way to improve your PHP scripts. This tutorial will get your started with the basics of loops in PHP.

foreach loops

Foreach loops were introduced in PHP 4. The foreach loop can only be used with arrays, they simply make it easier to iterate over elements in an array. There are two different ways to use the foreach loop, the second is just a useful addition to the first. Here's what a foreach loop looks like:

<?php

// first method

foreach($array as $value) {
    
// tasks to perform
}

// second method

foreach($array as $key => $value) {
    
// tasks to perform
}

?>

Using the first method, we can use the $value variable each time though the loop. This variable will contain the value of each array item. Using the second method, we can still use the $value variable, but now we can use the $key variable as well. The $key variable will contain the key of each array item.

Here is an example of how we can use each of these methods:

<?php

// First we need an array to loop over

$veggies = array(
    
'green' => 'luttuce',
    
'red' => 'tomato',
    
'purple' => 'eggplant',
    
'orange' => 'carrot'
);

echo 
"<p>Here is a list of vegtables:</p>";
echo 
"<ul>";

// Here's the first method
foreach($veggies as $value) {
    echo 
"<li>$value</li>";
}

echo 
"</ul>";


echo 
"<p>Would you like to know their colors?</p>";

// Here's the second method
foreach($veggies as $key => $value) {
    echo 
"$value is $key.<br />";
}

?>

Give the example code above a try to see what happens, then go on to the next page to read about for loops.

« Previous [ 1 2 3 ] Next »
Discuss Tutorial: Using Loops in PHP 4 Comments
Comment by Wock on Jun 7, 2006, 10:20 pm
Wonny doesn't know that, haha, wock used this tutorail today for wormy. Tongue I used it for my birthday drop-down boxes Smile

Yay for wonny, Smile!!
Comment by Ron on Jun 8, 2006, 6:22 am
Great, Glad it helped you. Smile
Comment by Ferimer5 on Jun 12, 2006, 11:32 am
Great turorial! Wink Smile Grin Cool Tongue
Comment by Zach Sinclair on Jun 18, 2006, 3:00 am
ShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShockedShocked

I'm confused Ron... I'm going to have to practice this part of PHP alot to get the hang of it! Thanks for the tutorial Ron! Smile

« Previous [ 1 ] Next »
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.