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?

3

5 Answers 5

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"];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks; using the generic "key" as a variable name made this easier to understand.
3

Do you mean:

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

2 Comments

Wow, too many answers too fast. I'll just add my bit, the docs link php.net/manual/en/control-structures.foreach.php
@adam, Cixate: To quote a response I got on another question: "On the simple questions you have to be fast and lucky to get da points. :-)"
1
$animal_types = array();
foreach($zoo as $aName=>$animal) {
  $animal_types[$aName] = $animal["type"];
}

Comments

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);

4 Comments

Then you lose the array! why would you want to do that?
@Neal: Which array do I loose?
@Neal: Which one, be specific please. Name it, so we can actually talk about something :)
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.
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) "*"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.