Forum Moderators: coopster
I have a function that uses variable variables which are defined outside the function.
I can't get it to work. I wondered if it even possible.
ex.
<?php
$a_foo = 'foo_not_bar';
$a_bar= 'bar_not_foo';
...
function showFooBar($which){
//$which here is of value foo or bar but in my case there's 250 values
$whichFooBar = '$a_'.$which
if(isset($$whichFooBar)) && ($$whichFooBar == 'foo')){
do something...
}
}
?>
it's the part in red I have trouble with - ie. accessing a variable variable's value oustide of the function scope.
I tried adding global $$whichFooBar but that doesn't seem to work either.
I shouldn't have use the $ sign in my new var declaration
$whichFooBar = '$a_'.$which;
becomes
$whichFooBar = 'a_'.$which;
$a_foo = 'foo_not_bar';
$a_bar = 'bar_not_foo';
function showFooBar($which)
{
//$which here is of value foo or bar but in my case there's 250 values
$whichFooBar = 'a_' . $which;
// print '<pre>'; print_r($GLOBALS); print '</pre>';
if (isset($GLOBALS[$whichFooBar]) && ($GLOBALS[$whichFooBar] == 'foo')) {
print $GLOBALS[$whichFooBar];
}
}
$a_foo_not_bar = 'foo';
showFooBar('foo_not_bar');