lundi 21 novembre 2016

Assign random class in php but limit the number of time a class can be attributed

Following a post on stackoverflow I was able to modify my code to assign a random class to my div's. The problem I am now facing is that since it's random, it's partially working with materializecss.

Basically when I have 5 or 6 posts to display I wanted to randomize the look and have various column sizing. There are only two options (either it's a 6 columns width, or a 3 column with). Each "row" should be 12 columns in total.

Here's my question: how can I limit the number of time the "col s12 m6 l6" class is given?

Here's the code :

if($count == 5):
            $the_class = array(
                'col s12 m6 l3',
                'col s12 m6 l6'
            );
            $rand = array_rand($the_class);
            if($count == 5)$class = $the_class[array_rand($the_class)];
            endif;

And then I echo the class :

<?php echo $class; ?>

When the random assignment is giving 3 times the "col s12 m6 l6" it's perfect but when it's more or less than it's not working. I understand that array_rand might not be the best way to accomplish this but it was by far the easiest method for me.

I was gonna use the same code with modifications for when I have 6 items to display. I believe that having either 2 or 4 times the "col s12 m6 l6" should do the trick for the second part.

Thank you




Aucun commentaire:

Enregistrer un commentaire