Have you ever needed to work out if an element is a multiple of a number? E.g. in a gallery if you have 10 images and every 5 images you want to change the class, you can do that by calculating to see if the image in question is a multiple of a number, in this quick tip I will show you how to do that!

Lets say you have an element .box-item, if you were to loop through the 3 items like so

<?php
    for($i=1;$i<=3;$i++){
        echo "<div class='box-item'>";
    }
?>

and the element .box-item has a definition of:

.box-item{
    width:190px;
    float:left;
    margin-right:15px;
}

The final item in the box above has exceeded the width available as there is a margin-right specified resulting in the final box dropping down a line and potentially ruining your layout.

The easiest way in PHP to get around this is to calculate whether each box is a multiple of 3 (3, 6, 9 etc…) and if it is specify no margin. The way to do this is below:

<?php
    function calculateMultiple($number,$multiple){
        if(($number % $multiple) == 0){
            return true;
        }
    }
?>

<?php
     for($i=1;$i<=3;$i++){

        $class = "";

        if(calculateMultiple($i,3)){
            $class = "nomargin";
        }

        echo "<div class='box-item $class'>";
    }
?>

So first we create a function that can run a quick calculation to see if the number is a multiple, initially set the $class variable with nothing, if it is a multiple we define the $class variable with “nomargin” resulting in your last box on each row having a class of no margin, the last thing you need to do is specify the class in your CSS file.

.nomargin{
    margin-right:0px;
}