You must use links.
In foreach, we move deeper from key to key. Var $ temp is a reference to the current element of the $ cat array. At the end, temp is the element we need.
<?php function set_catid(&$cats, $keys, $val) { $temp = &$cats; foreach($keys as $key) { $temp = &$temp[$key]; } $temp = $val; } $cats = array(); $keys = Array ('A', 'A2', 'A22', 'A221'); set_catid($cats, $keys, 'test'); print_r($cats); ?>
source share