1

I have a loop that has a dynamic variable in it, eg:

while(i < 10){
  echo  ${"dynamic" . $i . "var"};
  $i++;
};

I want to only echo the variable if the original var (say $dynamic3var) is set so I add:

while(i < 10){
  if(isset(${"dynamic" . $i . "var"})){
    echo  ${"dynamic" . $i . "var"};
  $i++;
  };
};

However this wont work as its still picking up $i.

Does anyone know a correct way of doing this?

2
  • what o/p you are getting on running the codes provided in answers ? Commented Jan 30, 2014 at 11:46
  • Plz post where you have declared the variable say $dynamic3var in the code Commented Jan 30, 2014 at 11:55

2 Answers 2

1

Since global variables are bad ideas you should rethink your code. A plain refactoring would be to use an associative array (even if it remains a global variable at the first step). Then you could work with

if( isset($dynamic[$i]) ) ...

Why are Globals evil? Read this: http://tomnomnom.com/posts/why-global-state-is-the-devil-and-how-to-avoid-using-it

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

Comments

0

Try this:

while($i < 10){
  $label = "dynamic".$i."var";

  if(isset($$label))
    echo $$label;

  $i ++;
};

3 Comments

Thanks but no luck there
Well then there is a bug elsewhere in your code or you aren't using an up to date PHP version. If I run the code on writecodeonline.com/php it works perfectly.
Give your explanation too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.