Reputation: 25
Below is a loop I have in my code. Once when the starting and ending values are a zero the loop prints a value zero (0). But what I need to do here is when the starting and ending value is zero, it should print nothing. Can someone please tell me how to change the approach?
while ($recQ = mysqli_fetch_array($runx))
{
for($ii=$recQ['start']; $ii<=$recQ['end']; $ii++)
{
if (!in_array($ii, $exclude))
{
echo $ii.", ";
}
}
}
Upvotes: 0
Views: 139
Reputation: 4716
You can try a bit of a different approach:
$resulting_set = array();
while( $recQ = mysqli_fetch_array($runx) ){
$my_set = range( $recQ['start'], $recQ['end'] );
$resulting_set = array_merge(
$resulting_set,
array_diff( $my_set, $exclude )
);
}
echo implode( ', ', $resulting_set);
The code is a bit easier to read and the result won't have the trailing comma + space you'd get from your version (Assuming you don't need it for some reason).
This is also easier to refactor because you can manipulate the array that contains the output a lot easier than outputting on the fly.
To remove 0's from the values, you could just add 0 to your $exclude array.
Upvotes: 0
Reputation: 173562
You can skip the execution of the inner loop by using continue;
in the main loop:
while ($recQ = mysqli_fetch_array($runx))
{
if ($recQ['start'] == 0 && $recQ['end'] == 0) {
continue; // skip the rest of the code inside this loop
}
for($ii=$recQ['start']; $ii<=$recQ['end']; $ii++)
Upvotes: 0