function pc_assign_defaults($array, $defaults) {
$a = array( );
foreach ($defaults as $d => $v) {
$a[$d] = isset($array[$d]) ? $array[$d] : $v;
}
return $a;
}
This function loops through a series of keys from an array of
defaults and checks if a given array, $array, has
a value set. If it doesn't, the function assigns a
default value from $defaults. To use it in the
previous snippet, replace the top lines with:
function image($img) {
$defaults = array('src' => 'cow.png',
'alt' => 'milk factory',
'height' => 100,
'width' => 50
);
$img = pc_assign_defaults($img, $defaults);
...
}
This is nicer because it introduces more flexibility into the code.
If you want to modify how defaults are assigned, you only need to
change it inside pc_assign_defaults( ) and not in
hundreds of lines of code inside various functions. Also,
it's clearer to have an array of name/value pairs
and one line that assigns the defaults instead of intermixing the two
concepts in a series of almost identical repeated lines.