PHP: Use a string as an array index path to retreive a value.

Posted by Charles on Stack Overflow See other posts from Stack Overflow or by Charles
Published on 2009-11-04T22:25:58Z Indexed on 2010/06/01 17:03 UTC
Read the original article Hit count: 217

Filed under:
|

Say I have an array like:

Array
(
    [0] => Array
        (
            [Data] => Array
                (
                    [id] => 1
                    [title] => Manager
                    [name] => John Smith
                )
         )
    [1] => Array
        (
            [Data] => Array
                 (
                     [id] => 1
                     [title] => Clerk
                     [name] =>
                         (
                             [first] => Jane
                             [last] => Smith
                         )
                 )

        )

)

I want to be able to build a function that I can pass a string to that will act as the array index path and return the appropriate array value without using eval(). Is that possible?

function($indexPath, $arrayToAccess)
{
    //$indexPath would be something like [0]['Data']['name'] which would return 
    //"Manager" or it could be [1]['Data']['name']['first'] which would return 
    //"Jane" but the amount of array indexs that will be in the index path can 
    //change, so there might be 3 like the first example, or 4 like the second.

    return $arrayToAccess[$indexPath] <-obviously wont work
}

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays