Search code examples
phparraysmultidimensional-arrayassociative-array

How do I assign names to keys when creating a PHP associative array with foreach?


Let's say I have an associative array listing animals at the zoo and some of their features, like so:

$zoo => array(
  "grizzly" => array(
    "type"      => "Bear",
    "legs"      => 4,
    "teeth"     => "sharp",
    "dangerous" => "yes"
  ),
  "flamingo" => array(
    "type"      => "Bird",
    "legs"      => 2,
    "teeth"     => "none",
    "dangerous" => "no"
  ),
  "baboon" => array(
    "type"      => "Monkey",
    "legs"      => 2,
    "teeth"     => "sharp",
    "dangerous" => "yes"
  )
);

Then I create a list of these animals like so:

$animal_types = array;
foreach($zoo as $animal) {
  $animal_types[] = $animal["type"];
}

Which outputs:

Array(
  [0] => "Bear",
  [1] => "Bird",
  [2] => "Monkey",
)

I would like this last array to be associative like so:

Array(
  ['grizzly']  => "Bear",
  ['flamingo'] => "Bird",
  ['baboon']   => "Monkey",
)

How do I create an associative array by pulling data from another array using foreach?


Solution

  • You just have to define the key in foreach loop, and then use the key of the current element of the first array, to specify the insertion key on the second array. Something like :

    $animal_types = array();
    foreach($zoo as $key=>$animal) {
       $animal_types[$key] = $animal["type"];
    }