Welcome Guest, Not a member yet? Register   Sign In
[SOLVED]counter doesn't increment when using if statement inside foreach loop
#1

[eluser]Nicholai[/eluser]
I have created a counter inside some nested foreach loops, but it only increments once, even if I run through the loop 20 times. Consider the following:

Code:
foreach($query_a as $row_a)
{
    $counter = 0;

    foreach($query_b as $row_b)
    {
        if ($row_b->ID == $row_a->ID)
        {
            $counter ++;
        }
        echo $counter;
    }
}

The counter is zero (if it never passes the test) or one (even if it passes a dozen times). Do I have something misplaced? If I move the counter outside of the IF statement it increments. Any advice is appreciated.
#2

[eluser]JoostV[/eluser]
Depends on what you want to count, really.

You are now counting the number of times $query_b is run inside a single loop, and you reset $counter to 0 for every $query_a loop.

Presuming you wish to count all instances where $row_b->ID == $row_a->ID, you should place $counter = 0 before the first foreach.

Code:
$counter = 0;
foreach($query_a as $row_a)
{
    foreach($query_b as $row_b)
    {
        if ($row_b->ID == $row_a->ID)
        {
            $counter ++;
        }
        echo $counter;
    }
}
#3

[eluser]Nicholai[/eluser]
That was it. I did more stuff based on the counter, but had the other stuff within the foreach, which was throwing me off.

Code:
$counter = 0;
foreach($query_a as $row_a)
{
    foreach($query_b as $row_b)
    {
        if ($row_b->ID == $row_a->ID)
        {
            $counter ++;
        }
        echo $counter;
    }
//next logic was here
}
//but should have gone here

Thanks for the advice!
#4

[eluser]JoostV[/eluser]
You're welcome Smile




Theme © iAndrew 2016 - Forum software by © MyBB