Get array value by multidim array of keys


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

The first argument is a variable name which value should be extracted from $array (second argument), or array of keys (multidim array is also supported).
The third argument is a default value which will be return on fail (false by default).

Usage examples:

1) $value = array_traverse('user[name]', $_POST);

2) $value = array_traverse(array('user' => array('name' => '')), $_POST);


Copy this code and paste it in your HTML
  1. function array_traverse($name, $array, $default = false) {
  2. $v = array();
  3.  
  4. if(is_string($name))
  5. parse_str($name, $v);
  6.  
  7. if(is_array($array) && is_array($v)) {
  8. $ref =& $array;
  9.  
  10. while(is_array($v)) {
  11. $first_key = key($v);
  12.  
  13. if(!is_null($first_key) && isset($ref[$first_key])) {
  14. $ref =& $ref[$first_key];
  15. $v = $v[$first_key];
  16. } else
  17. return $default;
  18. }
  19.  
  20. return $ref;
  21. }
  22.  
  23. return $default;
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.