Agaric Utility function: set default values in an array

Key words and phrases: 
array defaults
Description & Info: 

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.

Post new comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <small> <pre> <strike> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.