PHP array foreach – code snippets

PHP array – foreach loop on values

<?php
$a = array("v1", "v2", "v3");
foreach ($a as $val) {
  echo "$val ";
}
?>
v1 v2 v3 
Env: PHP 5.5.9 (Linux)

PHP array – foreach loop on index,values

<?php
$a = array("v1", "v2", "v3");
foreach ($a as $idx => $val) {
  echo "$idx $val ";
}
?>
Env: PHP 5.5.9 (Linux)

PHP array – foreach loop for modification

<?php
$a = array("v1", "v2", "v3");
foreach ($a as &$val) {
  $val = $val . "New";
}
print_r($a);
?>
Array
(
    [0] => v1New
    [1] => v2New
    [2] => v3New
)
Env: PHP 5.5.9 (Linux)

PHP associative array – foreach loop on values

<?php
$a = array("k1"=>"v1", "k2"=>"v2", "k3"=>"v3");
foreach ($a as $val) {
  echo "$val ";
}
?>
Env: PHP 5.5.9 (Linux)

PHP associative array – foreach loop on keys,values

<?php
$a = array("k1"=>"v1", "k2"=>"v2", "k3"=>"v3");
foreach ($a as $key=>$val) {
  echo "$key $val ";
}
?>
k1 v1 k2 v2 k3 v3 
Env: PHP 5.5.9 (Linux)
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments