1

I have a array:

$array = [
  0 => [],
  1 => ['name' => 'test']
  2 => ['name' => 'test 2']
];

I use function array_map for get name:

$names = array_map(function($item) {
      return $item['name'] ?? null;
}, $array);

I get "" in $names, how I can skip [] and get only names?

Dronax
  • 259
  • 2
  • 4
  • 15

2 Answers2

1

Normally the quick and dirty answer would be to do an array_filter after the array_map e.g.:

$names = array_filter(array_map(function($item) {
      return $item['name'] ?? null;
}, $array));

which is of course a long way of writing:

$names = array_column($array, 'name'));

See the manual for details on array_column

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

You should be able to remove empty array variables with array_filter()

https://www.php.net/manual/en/function.array-filter.php

Spudly
  • 310
  • 1
  • 2
  • 10