8

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.

5
  • like this: foreach($arr as $key=>$value) { .. } ? Commented Feb 20, 2013 at 5:36
  • Why do you require only while loop? Commented Feb 20, 2013 at 5:37
  • check my answer mate it's perfectly how you want........ Commented Feb 20, 2013 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 :) Commented Feb 20, 2013 at 5:43
  • How about mine marknt15........it's efficient and good one Commented Feb 20, 2013 at 5:49

5 Answers 5

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This is what I'm looking for :) I don't use while loop much in my projects, only for and foreach loop.
3

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

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

2 Comments

OP is aking to print them using while loop and not foreach function.
there is not much difference between while and foreach. Final result will be the same.
1

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

Comments

0

I have a simple solution for this, it will get the job done..

$x = array(0=>10,1=>11,2=>"sadsd");

end($x);    
$ekey = key($x);        
reset($x );

while(true){

    echo "<br/>".key($x)." = ".$x[key($x)];

    if($ekey == key($x) )break;
    next($x);
}

Comments

0

Try code below:

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

$obj = new ArrayObject($assocArray);

foreach ( $obj as $key => $value ) {
    echo '$' . $key .'='. $value . "<br/>";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.