0

Is it possible to get a result from array_column that has values only?

sample array i want to array_column

$array = [
   ['name' => ''],
   ['name' => 'John'],
   ['name' => 'Doe']
]

when i use array_column this is what i get

Array
(
    [0] => 
    [1] => John
    [2] => Doe
)

I was going to just use foreach and check each and every value but i was wondering if there is a much easier way to do this

thanks

royudev
  • 53
  • 6

2 Answers2

0

I think you want something like this (to get only the columns which has a value):

$array = [
    ['name' => ''],
    ['name' => 'John'],
    ['name' => 'Doe']
];

$result = array_filter(array_column($array, 'name'));

The array_filter will filter out empty names and you'll get something like this:

// print_r($result);

Array
(
    [1] => John
    [2] => Doe
)

Also, if you need to reorder the indices then you can use array_values like this:

$result = array_filter(array_column($array, 'name'));

// If you want to reorder the indices
$result = array_values($result);

// print_r($result);

Array
(
    [0] => John
    [1] => Doe
)
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

You could also do this to remove both null and empty values:

// PHP 7.4+
$result = array_filter(array_column($array, 'name'), fn($val) => !is_null($val) && $val !== '');

// PHP 5.3 and later
$result = array_filter(array_column($array, 'name'), function($val) { return !is_null($val) && $val !== ''; });
Clement Sam
  • 720
  • 7
  • 17