0

I have a use case whereby an array must be created that contains the key/value pairs that have an empty value in the original array.

This sample data is a simplified representation of the actual data. The code below results in the desired outcome but is there a more concise way to write this? Is there an alternative to using a foreach that's shorter than the code below?

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = [];
foreach ($data as $key => $value) {
    if (empty($value)) $result[$key] = $value;
}
echo print_r($result, 1);

Desired outcome:
enter image description here

knot22
  • 2,648
  • 5
  • 31
  • 51

1 Answers1

2

You can use array_filter() to do that:

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, fn($e) => empty($e));
print_r($result);

Output:

Array
(
  [peas] => 
  [turnips] => 
)

Demo PHP 7.4 : https://3v4l.org/hgZg8

Before PHP 7.4 and arrow functions, you can use an anonymous function:

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, function($e) { return empty($e); });
print_r($result);
Syscall
  • 19,327
  • 10
  • 37
  • 52