marknt15
marknt15

Reputation: 5127

PHP: How to print associative array using while loop?

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.

Upvotes: 8

Views: 19885

Answers (5)

Dmitry Leiko
Dmitry Leiko

Reputation: 4412

Try code below:

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

$obj = new ArrayObject($assocArray);

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

Upvotes: 0

Aylian Craspa
Aylian Craspa

Reputation: 466

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);
}

Upvotes: 0

Aris
Aris

Reputation: 5055

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

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

Upvotes: 3

Venkata Krishna
Venkata Krishna

Reputation: 4305

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

Upvotes: 11

Alfred
Alfred

Reputation: 21406

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

Upvotes: 1

Related Questions