Dmitry Lyalin Dmitry Lyalin - 10 months ago 50
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}[] = $Array;

Can someone helps or it imposoble?


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)) {
    } else if (!is_array($output[0]['follow']) {

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