0

I'm working on a function that looks like this:

public function myfunction($mainArr, $keys) {
    // $mainArr: a nested associative array
    // $keys: a simple array of strings, example: array('string_1', 'string_2', 'string_3')
    $totalKeys = count(keys);
    if(totalKeys == 1) {
        return mainArr[keys[0]];
    } else if(totalKeys == 2) {
        return mainArr[keys[0]][keys[1]];
    } else if(totalKeys == 3) {
        return mainArr[keys[0]][keys[1]][keys[2]];
    } else if(totalKeys == 4) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]];
    } else if(totalKeys == 5) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]][keys[4]];
    }
    // the same pattern continues..
}

I want to change this function into something more dynamic rather than a big list of "if" conditions, is it possible somehow?

1
  • you're missing the function keyword Commented Jun 13, 2013 at 16:27

1 Answer 1

1

You can do it for example this way:

function get_value(array $source, array $keys) {
    foreach ($keys as $key) {
        if (isset($source[$key])) {
            $source = $source[$key];
        }
        else {
            return null;
        }
    }

    return $source;
}

If $keys describes an invalid path inside $source then null will be returned.

Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly! I spent an hour just thinking of a solution, and you solved it in few seconds! You're a genius!
@evilReiko: I 'm no genius, just spent lots of time programming. As you learn you always find that yesterday's difficult task is today's easy thingy. This is true for everyone.

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.