Search code examples
phparraysarray-merge

PHP merge array if empty


Is there a nice way to merge two arrays in PHP.

My $defaults-array contains default values. If the $properties-array contains an empty string I want to use the value from the $defaults-array.

My code so far looks as following:

    $defaults = array( 
        'src' => site_url() . '/facebook_share.png',
        'alt' => 'Facebook',
        'title' => 'Share',
        'misc' => '',
        );


    $properties = array( 
        'src' => '',
        'alt' => '',
        'title' => 'Facebook Share',
        'text' => 'FB Text', //further properties
        );

$arr = array_merge( $defaults, $properties);
var_dump($arr);

Current result:

    $arr = array( 
        'src' => '',
        'alt' => '',
        'title' => 'Facebook Share',
        'text' => 'FB Text',
        'misc' => '',
        );

Desired result:

    $arr = array( 
        'src' => site_url() . '/facebook_share.png',
        'alt' => 'Facebook',
        'title' => 'Facebook Share',
        'text' => 'FB Text',
        'misc' => '',
        );

Hope someone can help.


Solution

  • Filter out the empties an then merge:

    $arr = array_merge($defaults, array_filter($properties));
    

    Keep in mind that array_filter will filter out elements that are empty string '', 0, null, false.