Zend - The PHP Company




Arrays

Add Code


array_fillup() - set default values absent in an array  

Type: code fragment
Added by: karsten
Entered: 01/12/2004
Last modified: 05/12/2008
Rating: - (fewer than 3 votes)
Views: 3204
With this function you can set up an array of defaults that should always be set, and then add those defaults to another array. his


<?php
/**
* Sets every value from $extra that is not present in $base.
*
* This means that the first array is expanded by every key/value pair
* in $extra, *if* there is no such key in $base already. In other words,
* if you see $extra as a set of default values, the result will be those
* default values, overwritten by stuff from $base, plus any extra data
* in $base.
*
* @param array $base Array to fill up (add defaults to).
* @param array $extra The array with the extra (default) data.
* @return array $base with values from $extra added.
*/
function array_fillup($base$extra)  {
  if (!
is_array($base) || !is_array($extra)) return false;

  foreach(
$extra as $k => $v) {
    if(!isset(
$base[$k])) {
      
$base[$k] = $v;
    }
    elseif(
is_array($base[$k])) {
      
$base[$k] = array_fillup($base[$k], $v);
    }
  }

  return 
$base;
}
?>


Usage Example


// we have a webapp with some defaults...

// reading configuration (with help of PEAR Config,
//                   readConfigfile is a custom function)
$conf = readConfigfile('tbconfig.ini');

// set default values for unset variables in $_GET.
$config = array_fillup($_GET,$conf);

// now $config contains your defaults with stuff in 
// $_GET overriding those defaults.


Rate This Script





Search



This Category All Categories