Krister Ross
Krister Ross

Reputation: 13

Cant get if sentence to work?

I am using a foreach loop to run through an array. With it I have $q which iterates with a value of 1 on every loop run. And when the value reaches 1/3 of the total, it is to echo out new div, in order to make several columns. But I cant seem to find the error.

            $i = 0;
            $count = count($segments->getItems());
            $countdiv = $count / 3;
            $countdiv = number_format((float)$countdiv,0,',','');
            $q = 0;
                foreach($segments->getItems() as $segment) 
                {
                    $q++;
                    $allusers = 0;
                    if($segment->getName() === 'All Users') {
                        $allusers = "checked";
                    }

                    ?>
                    <label class="custom-control custom-checkbox">
                        <input type="checkbox" name="<?php echo $segment->getName();?>" value="segments[]" class="custom-control-input" <?php echo $allusers?>>
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description"><?php echo $segment->getName();?></span>
                      </label>
                    <?php
                    if($q === $countdiv) 
                    {
                        ?>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="custom-controls-stacked">
                            <?php
                    }
                 }

Upvotes: 0

Views: 44

Answers (1)

Kallmanation
Kallmanation

Reputation: 1182

number_format() returns a formatted string of the number. So when you then compare that string to an actual number using ===, it will always be false, since a string type can never be strictly equivalent to a number type. Also, it would only work the first time around as $q is always increasing.

As @Chris Forrence recommends you can do:

if(($q % round($count / 3)) === 0)

Let's dive into that a little bit. First we divide $count by 3 since we want three columns. We can't divide on a fraction of an item, so let's round that result to a whole number. We then use that to take the modulo (%) of $q. This just says divide x / y but instead of the result, give me the remainder. So each time that $q is a multiple of $count / 3 this will return 0. So, if we test that whole calculation to see if it equals 0 then we will know when we've hit one of our column boundaries.

If you're looping over a large amount of objects and performance becomes an issue, change your $countdiv declaration to be:

$countdiv = round($count / 3)

And then the above if statement can be cut down to:

if(($q % $countdiv) === 0)

Upvotes: 1

Related Questions