pTutorial

New way to learn PHP

Foreach loop

foreach is a special kind of looping statement that works only on arrays. You can use it in two ways. You can either retrieve just the value of each element or you can retrieve the element's key and value.

Syntax of foreach loop

foreach ( $array as $value )
{
// (do something with $value here)
code to be executed
}

Example of access only value

<?php

$books = array
( 
"php", 
"java",
"c/c++", 
"database" 
);
foreach ( $books as $val ) 
{
echo $val ;
echo "
"; } ?>

In this example, $books is an array type variable that holds four elements and with the help of foreach loop we are accessing the element one by one.

access key and value example

<?php

$var = array(
'name'=> "john",
'branch' => "cse",
'year' =>2014,
 );
foreach( $var as $key => $value )
 {
echo "$key";
echo "=> $value " ."
"; } ?>

If you want to access value as well as key use the above method to access keys and values also.

Loops keywords

There are two special keywords that are used with loops, they are break and continue.

PHP Break keyword

Break takes an optional numeric argument which tells it how many nested enclosing structures are to take out.

Break keyword example

<?php

echo "Break keyword example
"; for ($test=0; $test<=20; $test++) { if ($test==7) { break; } echo "The number is ".$test; echo "
"; } echo "Another example of break"; echo "The number where loop break ".$test."
"; ?>

PHP continue keyword

Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

Continue keyword example

<?php

echo "Using continue statement
"; for ($var = 0; $var < 5; ++$var) { if ($var == 2) continue; print "$var
"; } <?php echo "Without continue statement
"; for ($var = 0; $var < 5; ++$var) { if ($var == 2) print "$var\n"; } ?>

It is not mandatory, to always use foreach loop in case of array, you can also use for loop. Following example shows an array with loop concept.

<?php
$fruits = array("mango", "banana", "orange");
$a = count($fruits);

for($x = 0; $x < $a; $x++) 
{
    echo $fruits[$x];
    echo "
"; } ?>

Output

mango
banana
orange

QUOTES OF THE DAY

Knowledge itself is a power.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER