March 9, 2012

Using a string path to set nested array data

Question by Anthony

I have an unusual use-case I’m trying to code for. The goal is this: I want the customer to be able to provide a string, such as:

"cars.honda.civic = On"

Using this string, my code will set a value as follows:

$data['cars']['honda']['civic'] = 'On';

It’s easy enough to tokenize the customer input as such:

$token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);

But now, how do I use $exploded path to set the array without doing something nasty like an eval?

Answer by alexisdm

Use the reference operator to get the successive existing arrays:

$temp = &$data;
foreach($exploded as $key) {
    $temp = &$temp[$key];
}
$temp = $value;
unset($temp);

Answer by Starx

Can’t you just do this

$exp = explode(".",$path);
$array[$exp[0]][$exp[1]][$exp[2]] = $value

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!