5

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
}
?>
danbae
  • 563
  • 2
  • 8
  • 22
  • Are you just wanting to print out the key and value of each of the array's elements? – Michael Millar Nov 18 '17 at 12:11
  • @Michael: I want to use the key and value both in the rest of my code, for a search routine.   •David: Yes, the problem and answer are the same, but the other post starts with quite a lengthy code snippet that makes it harder to identify the problem than here. Maybe I can keep my post unmarked as duplicate, or what is the etiquette? – danbae Nov 18 '17 at 12:24

2 Answers2

8

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;
}
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23
2

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";
}
?>
H. Sodi
  • 540
  • 2
  • 9