View Full Version : Simple Loop

03-10-2008, 04:19 AM
I've got a bunch of if statements that look like this:

if ($Variable1 !== "") {$VariableX = $VariableX + 1;}
if ($Variable2 !== "") {$VariableX = $VariableX + 1;}
Basically, I need to perform this for Variables 1 - 50. The numbered variable always increases by 1 (Variable1, Variable2, Variable3, and so on), and VariableX stays the same throughout all of the if statements.

Is there a loop of some sort I could use that would do this all automatically instead of manually for each individual variable?

Thanks in advance.

03-10-2008, 04:35 AM
You need to use an array.

When you have a set of same type data, using an array will result in the simplest and quickest code. Using consecutively named variables results in more complicated and the slowest operating code.

03-10-2008, 04:36 AM
instead of a whopping 50 vars, try putting them all in a array. Then you can use:

for($i=0; $i<50; $i++)
if ($variable[$i]!="")

That is untested, but its the basic idea

03-10-2008, 04:41 AM
Using a foreach() loop on an array eliminates the need to have a counter/index variable and you don't need to keep track of how many elements there are.

03-10-2008, 10:32 AM
To do what you want with the variables you have and if it will always be static you can do this:

for($i = 1; $i < 51; $i++)
$name = "Variable".$i;
if ($$name !== "")
$VariableX = $VariableX + 1;
}now this isn't the most efficient way of doing it though. Like everyone said using an array is ideal. It is easier and more efficient then a bunch of variables running around. Plus it allows for things to be dynamic. a simple use of count() on the array will give you how many elements are in the array or simple use foreach(). An example of using this to your advantage with what you have is this:

// Lets say you set the variables like so:

$Variable[] = 'asdf';
$Variable[] = '';
$Variable[] = 'asdf';

// This would be 3 elements which would be
// like your old $Variable1 $Variable2 $Variable3
// Now we loop through them with foreach()

foreach($Variable as $v)
if ($v !== "")
//$VariableX = $VariableX + 1; Lets change this
// This is assuming you already set $VariableX
// to 0 higher up

// The loop would result in $VariableX equalling 2
// Notice I also changed how it added $VariableX
// because its cleaner :P