1

I have an array named $row like this:

[multifield] => Array
(
    [pipelines_users] => Array
    (
        [users_id] => Array
        (
            [0] => 327
            [1] => 123
        )
    )
)

and I want to access the users_id array but only have the string multifield[pipelines_users][users_id]

But echoing $row[$string] uses the whole string as the key and doesn't parse the array notation of the square brackets.

I've tried: $row{$string} and several other incorrect syntax with no luck.

The string array notation will have variable keys so I can't hard code here.

2
  • If you don’t want to use eval, then you will have to do this using references - split the string into the sinlge keys, get the reference to the first level element via its key, and then use that reference to get the next level element, etc. Commented Oct 11, 2013 at 14:49
  • You are supposed to split the whole string into multiple substring if you want to access the single elements of the array.. Commented Oct 11, 2013 at 14:52

1 Answer 1

2

One way of achieving this without eval is to split the string up and loop through the keys, checking their existence, gradually narrowing down the array.

$row = array("multifield" => Array
(
    "pipelines_users" => Array
    (
        "users_id" => Array
        (
            0 => 327
            ,1 => 123
        )
    )
));
$str = 'multifield[pipelines_users][users_id]';
$parts = preg_split('#[[\]]+#',$str);//Convert string into array of keys: ('multifield','pipelines_users','users_id','')
$ret = $row;
foreach($parts as $key)
{
    if(isset($ret[$key])) $ret = $ret[$key];//When the key is found, we push $ret further down the array, for the next key search
}
var_dump($ret); //array(2) { [0]=> int(327) [1]=> int(123) } 
Sign up to request clarification or add additional context in comments.

3 Comments

@user2173785 No worries, glad to have helped.
sorry, actually I will have multiple arrays using these keys so need to access the array with all the keys so this won't work for me.
@user2173785 How do you mean? What's the issue? Do you need a function so you can apply the search to multiple arrays?

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.