Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 944
pbaldauf Avatar asked Feb 12 '23 15:02

pbaldauf


2 Answers

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.

like image 109
AbraCadaver Avatar answered Feb 14 '23 09:02

AbraCadaver


Try with this function

/**
  * @param {array} the properties array. transmitted by referance 
  * @param {array} the default array
  */
function getTheBest(&$properties, $defaults) {
    $temp = $properties;
    foreach ($properties as $key => $value) {
        if(empty($properties[$key]) && array_key_exists($key, $defaults) && !empty($defaults[$key]) ) {
            $properties[$key] = $defaults[$key];
        }
    }
}
like image 29
Halayem Anis Avatar answered Feb 14 '23 09:02

Halayem Anis