Return to Snippet

Revision: 26232
at April 21, 2010 08:32 by and


Initial Code
function array_traverse($name, $array, $default = false) {
    $v = array();

    if(is_string($name))
        parse_str($name, $v);

    if(is_array($array) && is_array($v)) {
        $ref =& $array;

        while(is_array($v)) {
            $first_key = key($v);
            
            if(!is_null($first_key) && isset($ref[$first_key])) {
                $ref =& $ref[$first_key];
                $v = $v[$first_key];
            } else
                return $default;
        }

        return $ref;
    }

    return $default;
}

Initial URL


Initial Description
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);

Initial Title
Get array value by multidim array of keys

Initial Tags
array

Initial Language
PHP