4

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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];
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.