Numeric 2 Associative

Convert a numeric array to associative.

Language: PHP

  1. <?php
  2.  
  3. // Here's the numeric array we want to convert
  4. $array = [
  5. 'apples',
  6. 'carrots',
  7. ];
  8.  
  9. // List of keys we want to use
  10. $keys = [
  11. 'fruit',
  12. 'vegetable',
  13. ];
  14.  
  15. foreach ($array as $k => $v) {
  16. $new_key = $keys[$k];
  17. $array[$new_key] = $v;
  18. unset($array[$k]);
  19. }
  20.  
  21. echo '<pre>';
  22. var_dump($array);
  23. echo '</pre>';
  24.  
  25. ?>

See It In Action