0

If I had an array such as:

testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));

How would I go about converting a string such as testarray[bar][0] to find the value its describing?

6
  • 1
    look on eval php.net/manual/en/function.eval.php Commented Jan 24, 2011 at 13:15
  • 3
    What are you trying to do? There may be better ways to do this Commented Jan 24, 2011 at 13:15
  • 1
    I agree with @Pekka -- I can't imagine a use-case for this that would be considered good practice. Commented Jan 24, 2011 at 13:19
  • I have a function that takes a parameter of a $_POST value and validates it, however it won't work with field values that are arrays, because $_POST['testfield[0][foo]'] != $_POST[testfield][0][foo] Commented Jan 24, 2011 at 13:31
  • You may want to prepend a $ to you variable name. Commented Jan 24, 2011 at 14:09

2 Answers 2

2

Well, you can do something like this (Not the prettiest, but far safer than eval)...:

$string = "testarray[bar][0]";

$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
    $variableName = $match[1]; // "testarray"
    if (!isset($$variableName)) {
        //Error, the variable does not exist
        return null;
    } else {
        $array = $$variableName;
        if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
            foreach ($matches[1] as $match) {
                if (!is_array($array)) {
                    $array = null;
                    break;
                }
                $array = isset($array[$match]) ? $array[$match] : null;
            }
        }
        return $array;
    }
} else {
    //error, not in correct format
}
Sign up to request clarification or add additional context in comments.

1 Comment

while the OP can achieve his goal by just calling check_post(&$_POST[testfield][0][foo]);
1

You could use PHP's eval function.

http://php.net/manual/en/function.eval.php

However, make absolutely sure the input is sanitized!

Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.