Reputation: 95
My PHP script's foreach cycle generates a div elements (product info and image width is 270px) into a bigger div (width 900px). And every new product info div is on new line but i want to have 2 or 3 div element on a one line. So if i have 8 products they should be on 3 or 4 lines, now i have these on 8 lines...
How to do it?
I appreciate any help!
Upvotes: 1
Views: 2909
Reputation: 1583
If you are using bootstrap then they have css for that in it otherwise this code will work for you
$count=0;
foreach (array_expression as $value)
{
if(count!=2)
{
<div style="float: left; margin: 0 20px 5px 0;">
<div> // create your div here
</div>
</div>
count++;
}
else
{
<div> // 3rd div
</div>
count=0;
}
}
Upvotes: 0
Reputation: 769
Why don't you try this ? for example you want three divs per line then wrap every three item in a wrapper div and float all the items to left and end every wrapper with a clear div :
$ct = 1;
foreach($array as $key=>$val){
if($ct%3==0) echo '<div class="wrapper">'; //start wrapper div
echo '<div style="float:left">'.$val.'</div>';
if($ct%3==0){
echo '<div style="clear:both"></div>';
echo '</div>'; //close wrapper div
}
$ct++;
}
Upvotes: 1
Reputation: 7762
Apart from all solutions one more way to achieve this. if you are looking solutions from foreach loop. you can break array by using array_chunk.
<?php
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// It will chunk array into 3,3 values.
$newArray = array_chunk($array, 3, true);
foreach ($newArray as $value) {
echo '<div class="separator">';
// Iterate inner arrays.
foreach ($value as $innerValue) {
echo $innerValue . ',';
}
echo '</div>';
}
Output:- Now inside separator div , 3 div will be displayed.
<div class="separator">1,2,3,</div>
<div class="separator">4,5,6,</div>
<div class="separator">7,8,9,</div>
Upvotes: 2
Reputation: 8659
If you want them to all be on one line, you should really use <span>
instead of <div>
See http://en.wikipedia.org/wiki/Span_and_div
There are multiple differences between div and span. The most notable difference is how the elements are displayed. In standard HTML, a div is a block-level element whereas a span is an inline element.
Or https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
<span>
is very much like a<div>
element, but<div>
is a block-level element whereas a<span>
is an inline element.
Upvotes: 0
Reputation: 338
you should use wrapper
echo '<div style="display: table" id="wraper">';
foreach($some as $key => $value){
// here you generate your divs for example:
echo '<div style="display: table-cell"></div>';
}
echo '</div>';
or you can use float css param on divs in foreach, when divs doesn`t have space in outer content they will drop to new line.
Upvotes: 0