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

12,375

Solution 1

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"];
}

Solution 2

Do you mean:

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

Solution 3

$animal_types = array();
foreach($zoo as $aName=>$animal) {
  $animal_types[$aName] = $animal["type"];
}
Share:
12,375
sea_monster
Author by

sea_monster

Updated on June 05, 2022

Comments

  • sea_monster
    sea_monster almost 2 years

    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?