Override defaults with options (PHP associative arrays)


/ Published in: PHP
Save to your folder(s)

Take an associative array of options and their default settings. Remove entries of options that do not exist in the default options. Return a safely filtered and overridden array of options.


Copy this code and paste it in your HTML
  1. <?php
  2. $defaults = array (
  3. 'default' => 'options',
  4. 'and' => 'values',
  5. 'go' => 'here',
  6. 'required' => true,
  7. 'filter_function' => null,
  8. 'error_string' => 'An error occurred: %s'
  9. ),
  10. $options
  11. ),
  12. $defaults
  13. )
  14. );
  15.  
  16. // Function Version
  17.  
  18. /**
  19.  * Takes an associative array of options and their default settings.
  20.  * Removes entries of options that do not exist in the defaults.
  21.  * Returns an array of options with the defaults where options do not
  22.  * override the defaults.
  23.  * @param array $options The user's options
  24.  * @param array $defaults The default options
  25.  * @return array The filtered and overridden options
  26.  */
  27. function safe_options ($options, $defaults) {
  28. return array_intersect_key(array_merge($defaults, $options), $defaults);
  29. }
  30.  
  31. extract(safe_options(
  32. $options,
  33. 'default' => 'options',
  34. 'and' => 'values',
  35. 'go' => 'here',
  36. 'required' => true,
  37. 'filter_function' => null,
  38. 'error_string' => 'An error occurred: %s'
  39. )
  40. ));
  41. print $default.$and.$go.$required.$filter_function.$error_string;
  42. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.