Reputation: 15404
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?
Upvotes: 1
Views: 1354
Reputation: 12388
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
Upvotes: 1
Reputation: 2399
Try this:
while($i < 10){
$label = "dynamic".$i."var";
if(isset($$label))
echo $$label;
$i ++;
};
Upvotes: 0