PHP - Set array key only if the value is not null

Viewed 2619

Is there a shorter solution for something like this?

$manufacturer = array();

if(!is_null($params->get('name'))){
    $manufacturer['name'] = $params->get('name');
}

if(!is_null($params->get('link'))){
    $manufacturer['link'] = $params->get('link');
}

if(!is_null($params->get('description'))){
    $manufacturer['description'] = $params->get('description');
}

...

So a key of an array should only be set with the value if the value is not null. This is a bit shorter, but with this solution the keys will exist with the value NULL. But they should not even exist when the value was NULL:

$manufacturer = array(
    'name' => !is_null($params->get('name')) ? $params->get('name') : null,
    'link' => !is_null($params->get('link')) ? $params->get('link') : null,
     'description' => !is_null($params->get('description')) ? $params->get('description') : null
);

EDIT:

It should work for multidimensional arrays and the array keys and param keys may vary

3 Answers
Related