what is foreach loop in php code example

Example 1: php foreach

$arr = ['Item 1', 'Item 2', 'Item 3'];

foreach ($arr as $item) {
  var_dump($item);
}

Example 2: foreach loop array php

foreach (array as $value){ 
  //code to be executed; 
  print("value : $value");
} 

foreach (array as  $key => $value){ 
  //code to be executed; 
  print("key[$key] => $value");
}

Example 3: for each php

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>

Tags:

Php Example