Click to See Complete Forum and Search --> : Scope Woes - IF statement nested in WHILE statement -PHP
hdogg
04-25-2007, 11:42 AM
I have an array $actuals_sum.
<?php
while(conditions)
{
if($i == '24)
{
$actuals_sum[$j] = 'bar';
$j = $j + 1;
}
}
echo $actuals_sum[1];
?>
---------
but.... it throws an ERROR and says $actuals _sum is undefined....
So the scope is LOCAL, i need to make it return GLOBAL.
-Hyrum
NogDog
04-25-2007, 03:56 PM
There is no scope difference in PHP inside or outside of loops (just within functions). My guess is that either (a) there is a flaw in your logic, or (b) you haven't shown us all you code and that, in fact, some of your code is within a function.
Perhaps for a quick sanity check you could print out the entire $actuals_sum array at different places where things should have happened to it, to see if they really did:
printf("<pre>%s</pre>\n", print_r($actuals_sum, 1));
hdogg
04-25-2007, 04:00 PM
Before I do the sanity check...
The array population takes place within an IF statement, not a function. I found that when i set variables in the IF statement that they stay local. Is that correct?
NogDog
04-25-2007, 04:17 PM
No, they are not local to the IF statement, if that's what you mean. They are within the same scope as the IF statement itself is.
$test = 'foo';
echo $test; // foo
if(true)
{
$test = 'bar';
}
echo $test; // bar
Scoping differences only occur inside/outside of function definitions (unless the variable is defined as "global" within the function definition).
Are you positive that your IF condition is actually ever evaluating as true?
hdogg
04-25-2007, 04:24 PM
Nogdog-
Thanks for the sanity check---
It helped me realize that the way I was writing my code my IF statement wasn't getting hit...
Thanks a bunch Nogdog -
Hdogg