I’m trying achieve a specific style for every 3rd 4th and 5th element in loop. I know it is possible in css but I want to learn it in php too. The following code inserts class to every 3rd element.
global $post_num;
if ( ++$post_num % 3 == 0 )
$class = 'whatever';
echo $class;
I’ve tried if ( ++$post_num % 3 == 0 ) && ( ++$post_num % 4 == 0 ) && ( ++$post_num % 5 == 0 )
, but it doesn’t work
The problem seems to be you are attempting to increment the
$post_num
multiple times within theif
clause. Try this instead.But that said, I am still unclear on what role the
++$post_num
plays since wouldnât this logic be placed in a larger loop? So wouldnât this work?Meaning
$post_num
is a value based on the content rolling through your script logic? And this clause will simply take the value of$post_num
and act on it? If you have more code to illustrate the structure you have in place that would help.EDIT Just adding my own loop for this example so itâs clearer what is happening.
But looking at the output it might not be what you expect, since 3rd, 4th or 5th with a modulus (
%
) operator will encompass a whole range of divisible items:ANOTHER EDIT Okay, I think I got it now. I am assigning the value of the modulus to the largest number to
$post_count
, then I set an array for the items you want to assign a class to in$class_value_array
and then theif
clause now usesin_array()
to validate.The output is now:
Which I am pretty sure is what you are looking for.
will give you the class on every gcd(3,4,5) = 60th row. Just do:
for five
for 4, etc.
It looks like you want to apply a separate style to the third, fourth, and fifth item. Why complicate things? Just add a class indicating that the element is the third, fourth, or fifth element in the series. You can use CSS to determine if an element is a combination. You don’t want to use CSS which I assume means you don’t want to use the
nth-child
selector.This code is not CSS/HTML only, you can easily change the code from applying a class to executing a function, for example.
Just style the classes at this point. Here’s the output: