0

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?

1
  • you need to use array_keys in conjuction with array map. the keys in array map is not accessible out of the box Commented Oct 21, 2021 at 2:53

2 Answers 2

2

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

$fruits = array_keys( $inventory )
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but I am trying to learn about array_map, the example I gave is a simple case. I am trying to figure out how to extract each key though a callback function.
You can't use array_map as it does not provide the keys on the parameter of the callback function so you might want to take a look at array_walk instead.
0

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

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.