Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extract key/value pairs where value is empty

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading