title: How to traverse associative array in PHP and access both key and data
body: <p>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."</p>
  
  <p>Example:</p>
  
  <pre><code>$array = ["one"=&gt;"un", "two"=&gt;"deux", "three"=&gt;"trois"];
  foreach ($array as $value){
      $key = array_search($value, $array);
      print_r($key);
      print_r($value);
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>Edit:
  5.28 seconds for 100k iterations on my machine. <code>php -a</code> </p>
  
  <pre><code>$start=microtime(true);for ($i = 0; $i &lt; 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);
  </code></pre>
  
  <p>5.3 seconds for:</p>
  
  <pre><code>$start=microtime(true);for ($i = 0; $i &lt; 100000; $i++){foreach($array as $key=&gt;$value){print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);
  </code></pre>
  
  <p>So no performance boost? The lack of difference is still there for a larger array:</p>
  
  <pre><code>$array = ["one"=&gt;"un", "two"=&gt;"deux", "three"=&gt;"trois", "four"=&gt;"quatre", "five"=&gt;"cinq", "six"=&gt;"six", "seven"=&gt;"sept", "eight"=&gt;"huit", "nine"=&gt;"neuf", "ten"=&gt;"dix"]; 
  </code></pre>