Agaric Utility function: set default values in an array
the original line is almost as short as the function, but if we want to add checking on "empty()" or need to change anything else, it's all in one place
<?php
/**
* Set a default value for an array key if that key does not exist.
*
* The _au_ namespace stands for agaric utility, and are things
* we may reuse in so many modules we'll want to put in a helper
* module or, better yet, in core.
*/
function agaric_au_default(&$array, $key, $default_value) {
if (!isset($array[$key])) $array[$key] = $default_value;
}
// use it:
agaric_au_default($form_values, 'type', 'lead');
?>
A more advanced version that provides feedback in the return value.
<?php
/**
* Set a default value for an array key if that key does not exist.
*
* If the key does exist, compare values and return TRUE if the same
* or the VALUE.
*
* If the key does not exist and the default value is assigned, return TRUE.
*
* The _au_ namespace stands for agaric utility, and are things
* we may reuse in so many modules we'll want to put in a helper
* module or, better yet, in core.
*
* @param array
* An array.
*
* @param key
* A string representing an array key.
*
* @param default_value
* A mixed value to assign to this key if one does not exist.
* @return mixed
*/
function salesforce_au_default(&$array, $key, $default_value) {
if (!isset($array[$key])) {
$array[$key] = $default_value;
return TRUE;
}
else {
if ($array[$key] == $default_value) return FALSE;
else return $array[$key];
}
}
?>
Historical note:
Originally to be used with even more abstract wrappage.
salesforce_expose_form_defaults($form_info); // passed by reference
encapsulating the whole thing per set of defaults is rejected for now because it does make it harder to see what you're doing.
But if these defaults should be applied in more than one place that wrapper would make sense.
Comments
Post new comment