Wednesday, 17 August 2016

PHP Basics : For Loops and For Each loops

Hi guyz

Lets see about for loop and foreach loop in PHP.

Lets begin your code

First we can see about FOR LOOP

FOR LOOP





<?php

$start = 0;
$end = 100; 

// Lets print numbers from 0 to 100

for ($start; $start <= $end; $start++) 
{
    echo "$start <br>";



?>


Now lets See how to use ForEach Loop in PHP

FOR EACH LOOP


<?php 

$fruits = array("Mango", "Orange", "Pineapple", "Guava", "Apple", "Pomegranate"); 

foreach ($fruits as $fruit) 
{
    echo "$fruit <br>";
}

?>

Its so simple right, Lets do something

Now i'm gonna implement for loop instead of for each in the above program


Lets begin your code



<?php

// Lets do above program using for loop
$fruits = array("Mango", "Orange", "Pineapple", "Guava", "Apple", "Pomegranate"); 
$total_fruits = count($fruits);
echo "$total_fruits <br>";
$array_end = $total_fruits - 1;
$array_start = 0;
for($array_start; $array_start <= $array_end; $array_start++)
{
echo "Array[$array_start] contains $fruits[$array_start] <br>";
}

?>


Its awesome right, In the above program count() is used to count the number of elements in an array.

Its pretty cool right ?

No comments:

Post a Comment