Home > OS >  Using array_map instead of foreach in PHP
Using array_map instead of foreach in PHP

Time:10-21

I have the following array:

$inventory = [
    'Apples' => ['Golden Delicious', 'Granny Smith','Fuji'],
    'Oranges' => ['Valencia', 'Navel', 'Jaffa']
];

What I would like to end up with is an array with the following:

['Apples','Oranges']

I can do:

$fruits = [];
foreach ($inventory as $key => $value) {
    $fruits[] = $key;
}

I am trying to educate myself on the use array_map, I tried:

$fruits[] = array_map('fruitTypes', $inventory);

function fruitTypes($item) {
    echo key($item)."\n";
    echo array_key_first($item)."\n";
    echo $item[0]."\n";
    //return something that will give me 'Apples' followed by 'Oranges'
}

But I am getting this:

0
0
Golden Delicious
0
0
Valencia

Any ideas?

CodePudding user response:

You can use array_keys, which returns an array of the keys of an associative array.

$fruits = array_keys( $inventory )

CodePudding user response:

Array Keys would do this, not array Map.

<?php

inventory = [
    'Apples' => ['Golden Delicious', 'Granny Smith','Fuji'],
    'Oranges' => ['Valencia', 'Navel', 'Jaffa']
];

$keys = array_keys( $inventory );

var_dump($keys);

Would produce:

array(2) {
  [0]=>
  string(6) "Apples"
  [1]=>
  string(7) "Oranges"
}
  •  Tags:  
  • php
  • Related