mpa
mpa

Reputation: 3

How can I define dynamically the associative array keys?

I have two variable:

$keystr = 'plant,fruit,exotic';
$value='kiwi'; 

how can i create the associative array?

$arr = ('plant'=>array('fruit'=>array('exotic'=>'kivi')));

Upvotes: 0

Views: 53

Answers (1)

Mark Baker
Mark Baker

Reputation: 212402

$keystr = 'plant,fruit,exotic';
$value='kiwi'; 

$arr = array();
$current = &$arr;
$keys = explode(',', $keystr);
foreach($keys as $key) {
    $current[$key] = array();
    $current = &$current[$key];
}
$current = $value;
unset($current);
var_dump($arr);

See http://ideone.com/YiMIRb for a demonstration

Upvotes: 3

Related Questions