I\'m using PHP to echo my products from DB. If we just use foreach will get the result one item per a loop but, Actually I want it echo two items per one times as below func
You can use the modulus operator to make the check. If your iterator is a multiple of two it will output the appropriate elements (it does this by checking that the remainder is zero):
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
$i = 0;
foreach ($data as $k => $row) {
if( ($i % 2) === 0) {
$out .= '';
}
$out .= '';
$out .= '';
$out .= '$' . $row['prod_price'] . '' . $row['prod_name'] . '
';
$out .= '' . $row['prod_descrip'] . '
';
$out .= '';
$out .= '';
if( ($i + 1) % 2 === 0 || ($i + 1) === count($data) ) {
$out .= '';
}
$i++;
}
}
return $out;
}
Note that the last bit ($i + 1) === count($data) is important in the event that your set holds an uneven number.