简体   繁体   中英

How to traverse associative array in PHP and access both key and data

I want to traverse an associative array in PHP and access both the key and the data in the most efficient way possible. This has got to be a duplicate, but I can't find a "best practice" example anywhere on SO that says "this is the definitive way to do it in PHP."

Example:

$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $value){
    $key = array_search($value, $array);
    print_r($key);
    print_r($value);
}

This is horrible; it traverses once per iteration when it searches for the key. Is there a better way to access the index of the array?

Edit: 5.28 seconds for 100k iterations on my machine. php -a

$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $value){$key = array_search($value, $array);print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);

5.3 seconds for:

$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $key=>$value){print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);

So no performance boost? The lack of difference is still there for a larger array:

$array = ["one"=>"un", "two"=>"deux", "three"=>"trois", "four"=>"quatre", "five"=>"cinq", "six"=>"six", "seven"=>"sept", "eight"=>"huit", "nine"=>"neuf", "ten"=>"dix"]; 
$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $index=>$value){
    echo $index . ' : ' . $value . '<br />';
}

It is indeed simple:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM