Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
?>
like image 501
danbae Avatar asked Jan 04 '23 04:01

danbae


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;
}
like image 68
Manuel Mannhardt Avatar answered May 16 '23 09:05

Manuel Mannhardt


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";
}
?>
like image 37
H. Sodi Avatar answered May 16 '23 09:05

H. Sodi