0
Q:

php loop associative array

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

foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    
}

//Key=Peter, Value=35
//Key=Ben, Value=37
//Key=Joe, Value=43
 
2
<?php


$person_with_age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

//echo "Peter is " . $person_with_age['Peter'] . " years old."; //just one

//now loop
foreach($person_with_age as $person => $age) {
  echo "Key=" . $person . ", Value=" . $age;
  echo "<br>";
}


?>
2
$arr = array(
  'key1' => 'val1',
  'key2' => 'val2',
  'key3' => 'val3'
);

foreach ($arr as $key => $val) {
  echo "$key => $val" . PHP_EOL;
}
1

New to Communities?

Join the community