2

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?

sea_monster
  • 659
  • 3
  • 8
  • 18

5 Answers5

4

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"];
}
Daniel García
  • 612
  • 4
  • 9
3

Do you mean:

foreach($zoo as $animal_name => $animal) {
    $animal_types[$animal_name] = $animal["type"];
}
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
  • 1
    Wow, too many answers too fast. I'll just add my bit, the docs link http://php.net/manual/en/control-structures.foreach.php – six8 Sep 14 '11 at 21:30
  • @adam, Cixate: To quote a [response](http://stackoverflow.com/questions/1342601/pythonic-way-of-checking-if-a-condition-holds-for-any-element-of-a-list/1342617#1342617) I got on another question: "On the simple questions you have to be fast *and* lucky to get da points. :-)" – Daniel Pryden Sep 14 '11 at 21:33
1
$animal_types = array();
foreach($zoo as $aName=>$animal) {
  $animal_types[$aName] = $animal["type"];
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
0
<?php
# holds the key names - only 4 defined
$key_names = array(
    'first',
    'second',
    'third',
    'last'
);

# holds the key values - 6 defined
$values_array = array(
    0.93,
    null,
    true,
    'a string here',
    'what about this?',
    '*'
);

# the new array that will have named keys
$new_array = array();

# used to match the current $values_array item index
# with the corresponding key name from $key_names 
$index = 0;

# parse the $values_array
foreach( $values_array as $values_array_entry ) {
    
    # assign the key name if it exists
  if( isset($key_names[$index]) ) {
        $new_array[ $key_names[$index] ] = $values_array_entry;
    } else {
        # this covers the case where there are fewer key names than key values
        # these keys would receive integer values starting with 0
        # using the current index for this example
        $new_array[$index] = $values_array_entry;
    }
    
    # increment the index by 1 after each pass
    $index++;
}

# output the new array
echo '<pre>';
var_dump($new_array);
echo '</pre>';
?>

Result:

array(6) {
  ["first"]=>
  float(0.93)
  ["second"]=>
  NULL
  ["third"]=>
  bool(true)
  ["last"]=>
  string(13) "a string here"
  [4]=>
  string(16) "what about this?"
  [5]=>
  string(1) "*"
}
George-Paul B.
  • 544
  • 4
  • 7
0

As you already have the keys, you only need to change the values. So copy over the zoo and change each value:

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

Or probably easier to grasp with a closure:

$animal_types = array_map(function($v){return $v["type"];}, $zoo);
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    Then you lose the array! why would you want to do that? – Naftali Sep 14 '11 at 21:34
  • @Neal: Which array do I loose? – hakre Sep 14 '11 at 21:35
  • @Neal: Which one, be specific please. Name it, so we can actually talk about something :) – hakre Sep 14 '11 at 21:37
  • That array is temporarily only, it's okay to loose it, infact, it's no loss at all. You might mean `$zoo`, but `$zoo` is not lost at all (`$animal` is set often to a copy of data to values that originate from `$zoo`, but it's actually a copy. `$animal_types` in the first example, and `array_map` is creating a copy anyway.) You might just have overlooked that. – hakre Sep 14 '11 at 21:40