0

I have a series of variables, I want to check if they are 0 or not, and if they are, I wish to redefine the variable to equal the string 'Unavailable'.

To do this I wrote a loop:

$indicators=array($admitted, $targeted, $cured, $defaulted, $total);

foreach($indicators as $indicator)
{   
if($indicator==0)
    {
    $indicator='Unavailable';
    }       
}

This checks to see if each of the variables in the array $indicators is equal to zero, and if so redefines it.

However, after this loop is closed a table is built using the variables:

$table1 .= '
            <tr>
                    <td>'.$year.'</td>
                    <td>'.$targeted.'</td>
                    <td>'.$admitted.'</td>
                    <td>'.$total.'</td>
                    <td>'.$cured.'</td>
                    <td>'.$defaulted.'</td>                 
            </tr>
            ';

The output of which includes some '0' terms - they are never substituted for the string 'Unavailable'.

I debugged the code with the following:

foreach($indicators as $indicator)
{
echo 'Before: '.$indicator;
if($indicator==0)
    {
    $indicator='Unavailable';
    }
    echo '<br />';
echo 'After :'.$indicator;
}

And confirmed that it was redefining the variables, but that redefiniton was not applying outside of the loop.

I feel this is an issue with scope - which I confess to not understanding well.

My question is: how can I get the variables defined inside a loop to apply outside of that loop?

Many thanks for your thoughts.

2 Answers 2

3

That's because all you're doing is updating the variable $indicator, not the original elements of the array.

There are 2 ways of doing this. Either pass by reference:

foreach($indicators as &$indicator)

or manually push the change back to the array:

foreach($indicators as $idx => $indicator)
{   
    if($indicator==0)
    {
        $indicators[$idx]='Unavailable';
    }       
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, didn't know about pass by reference before!
0

You are not assigning the changed value back to array

try this

foreach($indicators as $key=>$indicator)
{   
 if($indicator==0)
   {
  $indicator[$key]='Unavailable';
  }       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.