Looping a variable (PHP)

Soldato
Joined
27 Dec 2005
Posts
17,315
Location
Bristol
I have a list of variables, let's say $v1, $v2, $v3, $v4 etc. I want to do a while and check if their contents, whilst changing the digit during the loop. For example (though this doesn't work obviously).

while($num < 10){
if($v$num){
// do stuff
}
$num++
}

With the if() changing to $v1, $v2 etc as the while cycles through each time. How do I do this?
 
Couldn't you just put them all into an array or list (sorry not up on PHP) and then cycle through the array

List<MyVar) aryVars = new List<MyVar>()
aryVars.Add(MyVar1);
aryVars.Add(MyVar2);
etc

foreach(MyVar item in aryVars)
{
//do stuff
}

or

for(int i = 0; I < aryList.Count(); i++)
{
MyVar item = aryList.GetAt(i);
}
 
Assuming they are of the same type, then it would make sense to put them in an array container of some kind. If they are of different types, then iterating through them probably isn't appropriate.
 
This is a really bad practice way of dealing with variables. You don't want to be dynamically naming/referring to them like this in your code at all really.
 
Why do you need to be doing this? Just use the Array for what it's there for. If you need some sort of association, use key value pairs.
 
The actual answer to your question is this:

PHP:
while($num < 10){
  if(${'v'.$num}){
    // do stuff
  }
  $num++
}

But as others have said, an array is probably more suited to what you are doing.
 
Last edited:
As others have said, if you want to do this you're probably going about the whole process in the wrong way. Could you explain the exact situation you're trying to achieve?

Arrays in PHP are not 'arrays' in the traditional computing sense in that you're not restricted to a single data type. They work more like hashtables or Javascript objects (or indeed, JS arrays).

The docs have more info on them here: http://php.net/manual/en/language.types.array.php
 
Back
Top Bottom