Search code examples
phpvariable-variables

Iterate a series of variables which have incremented numeric suffixes


There are 10 variables. say $var1, $var2, $var3, $var4,....$var10

and a $count variable. what I am looking for is if all variables are set then $count = 10+1 or if 9 variables only set then $count=9+1 or if 8 variables only set then $count=8+1 and so on last up to 1 variable(for one variable is set then $count = 1+1).

I know do this with if, elseif and else but I need to write too much line of code.

Does any one know how to do this in brief code??


Solution

  • Try this (untested):

    $arr = array($var1, $var2, $var3, $var4, $var5, $var6, $var7, $var8, $var9, $var10);
    $count = 1;
    foreach ($arr as $v)
    {
        if (isset($v))
            $count++;
    }