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

2
  • Can you show what your expected results are? Commented Aug 5, 2020 at 18:33
  • my expected result should be [0 => 'John', 1 => 'Doe'] Commented Aug 6, 2020 at 16:39

2 Answers 2

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

1 Comment

Just be aware that this will filter out empty strings, false, null and 0.
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 !== ''; });

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.