Posted By

wyattstorch42 on 03/04/14


Tagged

php arrays options defaults associative


Versions (?)

Override defaults with options (PHP associative arrays)


 / Published in: PHP
 

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.

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

Report this snippet  

You need to login to post a comment.