Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - lookup array contents with dot syntax [closed]

Does anybody see anything wrong with the following function? (Edit: no, I don't think anything is wrong, I am just double-checking since this will be inserted into a very common code path.)

function getNestedVar(&$context, $name) {
    if (strstr($name, '.') === FALSE) {
        return $context[$name];
    } else {
        $pieces = explode('.', $name, 2);
        return getNestedVar($context[$pieces[0]], $pieces[1]);
    }
}

This will essentially convert:

$data, "fruits.orange.quantity"

into:

$data['fruits']['orange']['quantity']

For context, this is for a form utility I am building in Smarty. I need the name for the form also so I need the string to be in a key-based form, and can't directly access the Smarty variable in Smarty.

like image 832
Nicole Avatar asked Feb 18 '10 06:02

Nicole


1 Answers

Try an iterative approach:

function getNestedVar(&$context, $name) {
    $pieces = explode('.', $name);
    foreach ($pieces as $piece) {
        if (!is_array($context) || !array_key_exists($piece, $context)) {
            // error occurred
            return null;
        }
        $context = &$context[$piece];
    }
    return $context;
}
like image 61
Gumbo Avatar answered Oct 03 '22 22:10

Gumbo