Sunday 18 April 2021

Php: for-each loop

Using for-each loop, you can iterate over an array effectively. Foreach loop iterate over the elements of array one by one.

 

Syntax

foreach(array_name as key => value){
    
}

 

Example

foreach ($arr1 as $key => $val) {
    echo "$key => $val\n";
}

 

for_each_demo.php

#!/usr/bin/php

<?php
$arr1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

echo "Contents of arr1 are : \n";
foreach ($arr1 as $key => $val) {
    echo "$key => $val\n";
}

?>

 

Output

$./for_each_demo.php 

Contents of arr1 are : 
id => 1
age => 32
name => Sailu
male =>

 

If you are interested in only the values of array, you can use below syntax.

 

Syntax

foreach(array_name as value){
    
}

Example

foreach ($arr1 as $val) {
    echo "$val\n";
}


for_each_iterate_values.php

#!/usr/bin/php

<?php
$arr1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

echo "Contents of arr1 are : \n";
foreach ($arr1 as $val) {
    echo "$val\n";
}

?>


Output

$./for_each_iterate_values.php 

Contents of arr1 are : 
1
32
Sailu





 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment