Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a counter variable to a variable name

I don't understand how one can add a counter variable content to the name of another variable. Although I realized that my problem could be solved more elegantly with the use of arrays, I want to use the counter in the variable name.

My code looks like this so far:

    <?php
        $f2 = bla2;
        $f3 = bla3;

....

        $f13 = bla13;
        $f14 = 0;
        echo $f2;
        for($j = 3; $j <= 14; ++$j){
        if (!empty('$f'.$j)){
        echo(', ');
        eval('print $f'.$j.';');
        };
     };
     ?>

I want to give output for every $f and also check if it's empty before I echo it. The for loop already worked before adding the if condition. I assume that I don't name the variable correctly inside the if condition and I have no clue how to do it, as this code doesn't work as it is now.

I would also like to know, if I could include the if condition into the for loop. I already tried to apply the solutions to these questions

Access a variable using a counter as part of the variable name

Add counter to the end of variables?

Use counter as part of variable

but had no success so far. Maybe someone finds my mistake here.

like image 844
Jot Avatar asked Nov 30 '25 04:11

Jot


1 Answers

Something like this should work:

for ($i = 3; $i <= 14; ++$i) {
    if (empty(${"f$i"})) {
        ${"f$i"} = ${"bla$i"}();
    }
}

The bottom line is that you can use ${"f$i"} to find your variable variable.

like image 94
Ja͢ck Avatar answered Dec 02 '25 17:12

Ja͢ck