goodEgg goodEgg - 4 months ago 8
PHP Question

PHP - returning a variable variable from a function scope

Is there a way to return a variable variable from a function?

This is what I tried:

function varvar($num){
$var = "foo".$num;
return $$var;
}
varvar(3);
echo $foo3;


But nothing prints out. Any ideas?

Answer

You need to capture the return value in a variable:

function varvar($num){
    $var = "foo".$num;
    return $$var;
}
$foo3 = varvar(3);
echo $foo3;
Comments