Bertho Joris Bertho Joris - 4 months ago 7
PHP Question

How to make dynamic looping counter when using condition

I have a total data and I want to loop a number of data I had at the beginning. Only in the data enabling conditions whereby if the conditions are met then it will pass count counter and will be reduced. In sample case,

I need 10 data from loop

for ($i=1; $i <= 10; $i++) {
if($i == '8') {
echo "DATA PASSED : ".$i."<br>";
$i-1;
} else {
echo "SUCCESS : ".$i."<br>";
}
}


Result

SUCCESS : 1
SUCCESS : 2
SUCCESS : 3
SUCCESS : 4
SUCCESS : 5
SUCCESS : 6
SUCCESS : 7
DATA PASSED : 8
SUCCESS : 9
SUCCESS : 10


In In the case above, the result of looping my code is not right. No reductions resulting from the total looping.

The data should be 10. If I can see, I only get 9 data because the data of the 8th should be skipped.

How should I correct code and can generate

SUCCESS : 1
SUCCESS : 2
SUCCESS : 3
SUCCESS : 4
SUCCESS : 5
SUCCESS : 6
SUCCESS : 7
DATA PASSED : 8
SUCCESS : 9
SUCCESS : 10
SUCCESS : 11


Where the result is 10 data. Thanks

Answer

do while or a while loop should suit your case better. I am not a php expert, but this should work. More info on looping in php can be found here.

$counter = 1; 
$i= 0; // it should be start with 0

while($counter <= 10) {
    $i++;
    if($i == '8') {
            echo "DATA PASSED : ".$i."<br>";
    } else {
            echo "SUCCESS : ".$i."<br>";
            $counter++; 
    }
}