php: display key and value for each element of associative array

Viewed 16224

The following php snippet will display both the key and the value of each element in an associative array $ar. However, couldn't it be done in a more elegant way, such that the key and the value pointers are advanced by the same mechanism? I still would like it to be executed in a foreach loop (or some other that does not depend on knowledge of the number of elements).

<?php
$ar = array("A" => "one", "B" => "two", "C" => "three");
foreach($ar as $a){
    echo "key: ".key($ar)." value: ".$a."\n";
    $ignore = next($ar);//separate key advancement - undesirable
}
?>
2 Answers

Please read the manual. You can use foreach with the key as well like a so:

$ar = array("A" => "one", "B" => "two", "C" => "three");
foreach ($ar as $key => $value) {
    print $key . ' => ' . $value . PHP_EOL;
}

Problem You are using the foreach loop in the form of

foreach($array as $element)

This iterates through the loop and gives the value of element at current iteration in $element

Solution

There is another form of foreach loop that is

foreach($array as $key => $value)

This iterates through the loop and gives the current key in $key variable and the corresponding value in $value variable.

Code

<?php
$ar = array("A" => "one", "B" => "two", "C" => "three");
foreach($ar as $key => $value){
    echo "key: ".$key." value: ".$value."\n";
}
?>
Related