Explosion Explosion - 30 days ago 6
PHP Question

How can I skip the first if statement occuring in a loop?

I have made a loop to print table

<tr>
and
<td>

Here is my code:

echo "<tr>";
for($i = 0; $i < (int)count($fieldvalues); $i++){
echo "<td>" . $fieldvalues[$i] . "</td>";
if($i % 4 == 0){
echo "<td><input type='text'></td><td><input type='submit'
value='Add to cart'></td></form></tr>";
}
}


I want to skip the first
if
statement in the loop because the condition
$i % 4== 0
is true when $i is 0, that is,
0 % 4 == 0
.The value of
$fieldvalues
is 8. Any other method to overcome this is much appreciated.

Answer Source

Check that it is not 0 in the conditional.

if(!empty($i) && $i % 4 == 0){

or

if($i != 0 && $i % 4 == 0){

I'd also use a foreach rather than for.

A demo: https://3v4l.org/bG2NS