4

suppose i have a multidimensional array like something like this:

<?php

$array = array("test1" => array("test2" => array("test3" => 1)), ... foo1 = array("foo2" => 2));

?>

i want to access an array element by passing a string like "test1.test2.test3" to a function which in turn calls the array element. I could use eval() by replacing the string with [] (calling $array["test2]["test3"] ...) but i wonder if there is a different more solid approach in calling a array element without traversing through all of its depth or use eval().

2 Answers 2

5

You could use

function get_multi($arr, $str) {
    foreach (explode('.', $str) as $key) {
        if (!array_key_exists($key, $arr)) {
            return NULL; 
        }
        $arr = $arr[$key];
    }

    return $arr;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Symfony provides a PropertyAccess component for this.

The PropertyAccess component provides function to read and write from/to an object or array using a simple string notation.

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.