foreach loop in php
$browsers = $day1;
foreach($browsers as $browser)
{
echo "<input type='checkbox'/>$browser";
}
When I开发者_开发百科 use this code, it gives me output in single line, but I want to print two entries in single line and other in after the break.
Example:
1 2
3 4
5 6
Can anyone tell me how can we use a line-break in loop?
If this is the output you want:
browser1 browser2
browser3 browser4
...
browserN-1 browserN
You could try this:
$bIndex = 0;
foreach($browsers as $browser)
{
echo "<input type='checkbox'/>$browser";
if (($bIndex % 2) == 1) { // only true for odd bIndex values
echo "<br>";
}
$bIndex++;
}
From what you're saying, I think you mean you want to have each checkbox and label on a new line.
foreach($browsers as $browser){
echo '<p><input type="checkbox" /><label>'.$browser.'</label></p>';
}
Ofcourse, you'd want to be adding a name
attribute on each the input tags (and the label
tags), if you wanted to be able to process them on the server side.
If I got you correctly you want to show two in each line than after a break, try this
echo "<p>";
for($i=0;$i<count($browsers);$i++) {
if($i>0 && ($i%2==0)) { echo "</p><p>"; }
echo "<input type='checkbox' name='browser[".$browsers[$i]."]' /><label>".$browsers[$i]."</label>";
}
echo "</p>";
Edit for comment:
if it's not enumerated, still easy:
$i=0;
echo "<p>";
foreach ($browsers as $randomstuff=>$browser) { //or whatever array structure.
if($i>0 && ($i%2==0)) { echo "</p><p>"; }
echo "<input type='checkbox' name='browser[".$browsers."]' /><label>".$browsers."</label>";
$i++;
}
echo "</p>";
精彩评论