Posted By

and on 04/21/10


Tagged

array multidimensional


Versions (?)

Get array value by multidim array of keys


 / Published in: PHP
 

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 = arraytraverse('user[name]', $POST);

2) $value = arraytraverse(array('user' => array('name' => '')), $POST);

  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  

You need to login to post a comment.