Tag Archives: php array

What is foreach loop in PHP?

20 Dec

PHP is full equipped language with good number of inbuilt function and properties.

Since PHP is with 3 types of array like , Numeric array , Associative Array and Mixed Array.

To get data from array foreach loop can be used which is specially designed to retrieve records from complex structure like array and array of objects etc..

Definition of Foreach Loop :

foreach( array_name as array_key => array_value){
expression 1;
expression 2;
.........
expression n;
}

Description :

Input of foreach loop is any array i.e array_name having combination of array key and array value. foreach loop will iterate till the numer of records available inside given array.

Output of foreach loop will be key and value of given array.

array_key will handle offset value of an array which is called as key

array_value will handle actual record which is called as value.

( => ) is called as associative operator in PHP.

Associative operator ( => ) is used to link the relation between key and value e.g ( [0] => PHP  where 0 is the key and PHP is its value).

Example of Foreach Loop:

$country = array("India" , "United States" , "Nepal" , "Brazil" );
foreach( $country as $value)
{
echo $value;
echo "<br />";
}

Explanation :

In the above example , $country is an array having total 4 value .

When we do foreach loop , foreach loop will first count the number of records available in $country array . Then it will extract one by one record in $value. so the answer of above example will be displayed as below:

Answer :

India 
United States
Nepal
Brazil