Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to print associative array using while loop?

Tags:

arrays

php

I have a simple associative array.

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

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

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

This is my current solution but I think that this is not the efficient/best way to do it?

<?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 />';
};
?>

Thanks.

like image 887
marknt15 Avatar asked Feb 20 '13 05:02

marknt15


1 Answers

try this syntax and this is best efficient way to do your job...........

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 reference please check this link.........

Small Example link here...

like image 93
Venkata Krishna Avatar answered Oct 21 '22 20:10

Venkata Krishna