php array loop key value code example

Example 1: php loop through array

$clothes = array("hat","shoe","shirt");
foreach ($clothes as $item) {
	echo $item;
}

Example 2: php for array key value

<?php
$array = array(1=>"apple",2=>"Orange",3=>"Banana");

foreach($array as $key => $value){
	echo "The value for " . $key . " is " . $value;
}
/*The value for 1 is apple
The value for 2 is Orange
The value for 3 is Banana

$array = [1 => "apple", 2 => "Orange", 3 => "Banana"    
    Is also valid
];*/  
?>

Example 3: php foreach

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {
  echo "$x = $val<br>";
}
?>

Example 4: php ofreach

<?php

$a = array(1, 2, 3, 17);

foreach ($a as $index => $v) {
    echo "Current value of \$a: $v.\n";
}

?>

Example 5: loop over keys and values php

foreach ($arr as $key => $value) {
 echo $key;
}

Tags:

Php Example