3

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

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.