User login

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.

Resolution

Searched words: 
array defaults

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.