Dmitry Lyalin Dmitry Lyalin - 5 months ago 19
PHP Question

PHP Variable variables and array key veriables

I try to create code with out IF:

if ($lvl == 0) {
$OutPutArray[0]['follow'][] = $infoArr;
} elseif ($lvl == 1) {
$OutPutArray[0]['follow'][0]['follow'][] = $infoArr;
} elseif ($lvl == 2) {
$OutPutArray[0]['follow'][0]['follow'][0]['follow'][] = $infoArr;
}


And i whant it to be unlimited)) So i need something like:

$prefix="[some_key]...[some_key]";
${$prefix}[] = $Array;


Can someone helps or it imposoble?

Answer

You can't use variable variables to describe array dimensionality (well, actually you can, if you eval the string, but that's horrible and dangerous).

If it were me, and I couldn't avoid the problem (it looks somewhat suspect) then I'd use a recursive function.

function setOuput(&$output, $lvl, $infoArr)
{
    if (!is_array($output)) {
       $output=array('follow'=>array(0=>false));
    } else if (!is_array($output[0]['follow']) {
       $output[0]['follow']=array();
    }

    if (!$lvl) {
       $output[0]['follow'][0]=$infoArr
    } else {
       setOuput($output[0]['follow'][0], $lvl-1, $infoArr);
    }
}
Comments