0

I have a script where I retrieve several values from a database and i store them in the following variables:

$Av_1o=99;
$Av_2o=100;
$Av_3o=80;
$Av_4o=70;
$Av_5o=90;
$Av_6o=110;
$Av_7o=120;
$Av_8o=110;
$Av_9o=90;
$Av_10o=88;
$Av_11o=99;
$Av_12o=100;
$Av_13o=101;

Then, depending on another variable, such as year, i have to set a max value in the counter (named: $top_counter):

//defining year:
$year=2009;
            switch($year){
        case 2008:
            $top_counter=13;
            break;
        case 2009:
            $top_counter=11;
            break;
        case 2010:
            $top_counter=9;
            break;
        case 2011:
            $top_counter=7;
            break;
        case 2012:
            $top_counter=5;
            break;
        case 2013:
            $top_counter=3;
            break;
        case 2014:
            $top_counter=1;
            break;
        default:
            $top_counter=NULL;
    }

Finally, i use a for loop:

for($counter=1;$counter<=$top_counter;$counter++){
  $variable_name='Av_'.$counter.'o';
  if($$variable_name>=100){
    echo '<p style="color: green;">'.$variable_name.' is equal or greater than 100</p>';
  }
}

my question is how i can tell php which variable (declared on the top) to use depending on the corresponding number ($counter)?

For this case, the output i get, when year is 2009 is the following:

Av_2o is equal or greater than 100

Av_6o is equal or greater than 100

Av_7o is equal or greater than 100

Av_8o is equal or greater than 100

How can i print the variable name? or know exactly which $Av_xo i am currently using?

Thanks!

Pathros
  • 10,042
  • 20
  • 90
  • 156

2 Answers2

1

You could store your database values in an array, and use the counter as its index:

$array = array("foo", "bar", "hello", "world");
for($counter=0; $counter<=$top_counter;$counter++){
    var_dump($array[$counter]);
}

Note the change from $counter=1 to $counter=0, as array's indexing starts with 0 (e.g. in the array above, $array[0] = "foo" and $array=[2] = "hello")

binaryatrocity
  • 956
  • 5
  • 10
1

I wouldn't use a standard variable to do this. Not only are you creating an indeterminate number of variables, you're basically building an array, which is more easily managed for what you want to do.

$av = array();
while($row = mysqli_fetch_assoc($someresultset)) $av[] = $row['field'];

for($counter=1;$counter<=$top_counter;$counter++){
  if($av[$counter] >= 100){
    echo '<p style="color: green;">'.$av[$counter].' is greater than 100</p>';
  }
}
Machavity
  • 30,841
  • 27
  • 92
  • 100