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.
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
.
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];
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With