Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
like this: foreach($arr as $key=>$value) { .. } ? –  Thrustmaster Feb 20 '13 at 5:36
 
Why do you require only while loop? –  Angelin Nadar Feb 20 '13 at 5:37
 
check my answer mate it's perfectly how you want........ –  Venkat Feb 20 '13 at 5:43
 
Hi Thrustmaster, I know how to do it in foreach and for loop but I don't know the efficient way to do it in while loop so that's why I want to know :) –  marknt15 Feb 20 '13 at 5:43
 
How about mine marknt15........it's efficient and good one –  Venkat Feb 20 '13 at 5:49
add comment

3 Answers

up vote 5 down vote accepted

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...

share|improve this answer
 
Thanks. This is what I'm looking for :) I don't use while loop much in my projects, only for and foreach loop. –  marknt15 Feb 20 '13 at 5:50
add comment

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

 foreach ($assocArray as $key => $value)
        echo $key . ' = ' . $value . '<br />';
share|improve this answer
 
OP is aking to print them using while loop and not foreach function. –  blasteralfred Ψ Feb 20 '13 at 5:40
 
he asking in while loop not foreach.......... –  Venkat Feb 20 '13 at 5:42
 
there is not much difference between while and foreach. Final result will be the same. –  Aris Feb 20 '13 at 7:00
add comment

Try this;

$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 />';
};
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.