shibbir ahmed shibbir ahmed - 7 months ago 30
PHP Question

how can I add a class in php while loop?

I am trying add 2 bootstrap class

col-md-8
after 1 loop and then 2
col-md-4
class in php while loop. This process should be same in full while loop. So the result will look like this :

enter image description here

My current code is bellow but it's not showing the result what I need, can't get an idea how the loop will like !

Full code :

<div class="row text-center">
<h2>What we offer</h2>
<hr class="separator">
<?php $get_menu_class=m ysqli_query($conn, "SELECT pcat_name, pcat_image FROM product_category ORDER BY pcat_id DESC"); $x=0; while($menu_class_result=m ysqli_fetch_array($get_menu_class) ) { $menu_class_name=h tmlspecialchars($menu_class_result[ 'pcat_name']); $menu_class_image=h tmlspecialchars($menu_class_result[ 'pcat_image']); if($x & 1) { $col='8' ; }else { $col='4' ; } ?>
<div class="col-sm-<?php echo $col; ?>">
<div class="we-offer">
<a href="area">
<img src="<?php echo IMG_DIR."/menu_class/$menu_class_image"; ?>" alt="" class="img-responsive center-block">
<h3><?php echo ucfirst($menu_class_name); ?></h3>
</a>
</div>
</div>
<?php $x++; } ?>

</div>


Latest code :

<div class="row text-center">
<h2>What we offer</h2>
<hr class="separator">
<?php $get_menu_class=m ysqli_query($conn, "SELECT pcat_name, pcat_image FROM product_category ORDER BY pcat_id DESC"); $x=0; while($menu_class_result=m ysqli_fetch_array($get_menu_class) ) { $menu_class_name=h tmlspecialchars($menu_class_result[ 'pcat_name']); $menu_class_image=h tmlspecialchars($menu_class_result[ 'pcat_image']); $col=( (($x+1)/2)%2)? "8": "4"; ?>
<div class="col-sm-<?php echo $col; ?>">
<div class="we-offer">
<a href="area">
<img src="<?php echo IMG_DIR."/menu_class/$menu_class_image"; ?>" alt="" class="img-responsive center-block">
<h3><?php echo ucfirst($menu_class_name); ?></h3>
</a>
</div>
</div>
<?php $x++; } ?>

</div>


Current Result :

[![enter image description here][2]][2]

Answer

Try this logic please: $col = ((($i+1)/2)%2)?"8":"4";

https://3v4l.org/GHGVp

As you can see it outputs the desired results.

The col for loop 0 is col4
The col for loop 1 is col8
The col for loop 2 is col8
The col for loop 3 is col4
The col for loop 4 is col4
The col for loop 5 is col8
The col for loop 6 is col8
The col for loop 7 is col4
The col for loop 8 is col4
The col for loop 9 is col8
The col for loop 10 is col8
The col for loop 11 is col4
The col for loop 12 is col4
The col for loop 13 is col8
The col for loop 14 is col8
The col for loop 15 is col4
The col for loop 16 is col4
The col for loop 17 is col8
The col for loop 18 is col8
The col for loop 19 is col4

You just need to replace in your code the

if($x & 1) {
    $col = '8';
}else {
    $col = '4';
}

with

$col = ((($x+1)/2)%2)?"8":"4";
Comments