2

I'm retrieving my items from Exact and displaying them usuing a PHP loop. However, i want to put a HTML tag (br) after every 3 items.

Is there a possibility to do this? My current code:

<?php
    $glas = getGLAccounts($search);
    $count = 0

    foreach($glas as $gla) {
        $count++;
        echo "<tr><td><a href='glaccountedit.php?glaccount=".$gla['ID']."'>".$gla['Code']." </a></td><td>&nbsp;&nbsp;&nbsp;".$gla['Description']."</td></tr>";

        if ($count == 3) {
            echo "</br>";
        }
    }
?>

However, this isn't working. What am I doing wrong?

4
  • 1
    stackoverflow.com/questions/9992396/… Commented Nov 30, 2016 at 8:59
  • 1
    if($count % 3 == 0) Use the modulo operator. Commented Nov 30, 2016 at 8:59
  • You need to reset the counter to start over Commented Nov 30, 2016 at 9:00
  • You don't reset your counter. Inside if ($count == 3) { add $count = 0. But I think @nicovank solution is way better. Commented Nov 30, 2016 at 9:01

2 Answers 2

3

Your code will put <br> only once. If you need to put after each three items you need to reset your variable:

if ($count == 3) {
    $count = 0;
    echo "</br>";
}

or change condition:

if ($count%3 === 0) {
    echo "</br>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

It doesn't work because your Count isn't reset. If count == 3, it will do a <br> but after this, count is again increased. So count will be 4, 5, 6, 7, etc and never again be true for count == 3

<?php
$glas = getGLAccounts($search);
$count = 0

foreach($glas as $gla) {
    $count++;
    echo "<tr><td><a href='glaccountedit.php?glaccount=".$gla['ID']."'>".$gla['Code']." </a></td><td>&nbsp;&nbsp;&nbsp;".$gla['Description']."</td></tr>";
    if ($count == 3) {
        $count = 0;
        echo "</br>";
    }
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.