Loops


There are a few different kinds of loops in PHP. There is the standard "For" loop, the "While" loop, and the "foreach" loop. The for loop takes an initialization variable, which determines where the count will start, a condition for when the loop will break (as in what value of count will the loop break), and an increment which will change the count each iteration of the loop. The while loop sets a condition that, while true, the loop will continue to iterate. Once the condition is broken, the while loop will break. The last loop is the foreach, which will loop through an array, and for each element it will execute the body of the loop.

I have a code example below for some really basic code examples for uses of the different kinds of loops. The most elaborate example is the foreach loop, for which I built an array of arrays containing product information for different products. The foreach loop goes through each item in the products array and prints all of the information in them. The indices are named for what they represent so each product has a name, price, and a special attribute called 'top'

<?php
//array() function builds an array with the given elements
$lpStd = array('name' => 'Les Paul Standard', 'price' => 2500, 'top' => '2AFlamed Maple');
$lpClsc = array('name' => 'Les Paul Classic', 'price' => 2000, 'top' => 'Maple');
$lpStud = array('name' => 'Les Paul Studio', 'price' => 1500, 'top' => 'None');
$lpTrib = array('name' => 'Les Paul Tribute', 'price' => 1000, 'top' => 'None');
$n=0;
$products = array($lpStd, $lpClsc, $lpStud, $lpTrib);
for($i = 0; $i <= 3; $i++){
 echo $i;
}
echo '<br />';
foreach($products as $product){
 echo $product['name'] . ' - ' . $product['price'] . ' - ' . $product['top'];
 echo '<br />';
}
while($n<4){
 echo $n;
 echo '<br />';
 $n++;
}

 ?>

Comments

Popular posts from this blog