user747796
user747796

Reputation: 43

how to create a line break in a loop

In the code below I would to add a break tag tag after the radio button displays 5 times. I tried few ways but keep getting the entire number of radio button to repeat.

foreach ($salary_tbl as $key=>$value) {
    echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
  }

this is what I tried

for ($i=1; $i<=10; $i++) {
 if ($i < 5) {
    foreach ($salary_tbl as $key=>$value) {
     echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
   }
  }
 }

Thanks

Upvotes: 2

Views: 9198

Answers (5)

WeSo
WeSo

Reputation: 36

$i = 0;
foreach ($salary_tbl as $key=>$value) {
    if ($i >= 5) {
      // Line break
      $i=0;
    }
    echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
    $i++;
}

Upvotes: 0

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25755

$count = 0;
foreach ($salary_tbl as $key=>$value) {
    if($count == 5) {
         //Apply the line break here
    }
    echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
    $count++;
}

or if you want the line break every 5 records then you can slightly change the code to.

$count = 0;
foreach ($salary_tbl as $key=>$value) {
    if($count && $count%5 == 0) {
         //This will apply the line break for every five records
    }
    echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
    $count++;
}

another suggestion of mine is, instead of using escape character \ you could simply use it with single quotes and concatenation operator which is much more readable.

for example.

echo '<span class="year">' . $key . '</span><input class="margin_r36" type="radio" value="' . $value . '" name="salary_tbl"/><br />';

isn't it much more readable now?

Upvotes: 5

SoWhat
SoWhat

Reputation: 5622

If I am right you want the break repeated every 5 radio buttons. You can use modulus. IF the count is divisible by 0(that is its 5 10 15 20...), then we add a break

$count=0;
foreach ($salary_tbl as $key=>$value) {
if($count and $count%5==0) echo "<br/>";
echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' /><br />";
$count++;
 }

Upvotes: 1

brense
brense

Reputation: 412

$n = 0;
foreach ($salary_tbl as $key=>$value) {
    echo "<span class=\"year\">$key</span><input class=\"margin_r36\" type=\"radio\" value='$value' name='salary_tbl' />";
    if($n % 5 == 0){
        echo "<br />";
    }
    $n++;
}

Upvotes: 1

RobinUS2
RobinUS2

Reputation: 955

If you want a break every 5th line you could use modulo:

if ($i % 5 == 0) { 
  // line break
}

Upvotes: 0

Related Questions