PHP: How to print an associative array using a while loop?

I have a simple associative array.

<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
?>

Using only the while loop, how can I print it in this result?

$a = 1 
$b = 2 
$c = 3

This is my current solution, but I think this is not an efficient / best way to do this?

<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocArray);
rsort($keys);

while (!empty($keys)) {
    $key = array_pop($keys);
    echo $key . ' = ' . $assocArray[$key] . '<br />';
};
?>

Thank.

+5
source share
3 answers

try this syntax and it is the best efficient way to get your work done ...........

while (list($key, $value) = each($array_expression)) {
       statement
}

<?php


$data = array('a' => 1, 'b' => 2, 'c' => 3);

print_r($data);

while (list($key, $value) = each($data)) {
       echo '$'.$key .'='.$value;
}

?>

For the link , please check this link .........

A small example here ...

+8
source

The best and easiest way to loop through an array is to use foreach

 foreach ($assocArray as $key => $value)
        echo $key . ' = ' . $value . '<br />';
+3
source

Try it;

$assocarray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocarray);
rsort($keys);
while (!empty($keys)) {
    $key = array_pop($keys);
    echo $key . ' = ' . $assocarray[$key] . '<br />';
};
+1
source

All Articles