简体   繁体   中英

How do I use a variable inside of a shorthand if/else statement in a PHP for() loop?

I am trying to use a FOR loop to write dynamic CSS. The CSS needs to change based on how many items are in a database table. Here is my attempt, but it is not giving me the output I desire:

    <?php
    $count_posts = wp_count_posts( 'portfolio' )->publish; // This is for a wordpress site.
    $slidecount = ceil( $count_posts / 3 ); // there are 3 database entries in each "slide".

    for ($c = 0 ; $c < $slidecount; $c++){ 
    echo '#slide' . ($c + 1) . ':checked ~ #controls label.c-label' . ($c < $slidecount ? (($c + 2) . ', ') : '1'); // This is the part I'm not sure on... How do I properly nest the ($c + 2) expression into a shorthand if/else statement ??
    }
    echo ' {' . "\n" . 'float: right;' . "\n" . 'display: block; }' . "\n";
    ?>

Output (when there are 5 items in the database table):

            #slide1:checked ~ #controls label.c-label2, 
    #slide2:checked ~ #controls label.c-label3, 
    #slide3:checked ~ #controls label.c-label4, 
    #slide4:checked ~ #controls label.c-label5, 
    #slide5:checked ~ #controls label.c-label6 {
    float: right;
    display: block;
    }

Desired output:

    #slide1:checked ~ #controls label.c-label2, 
    #slide2:checked ~ #controls label.c-label3, 
    #slide3:checked ~ #controls label.c-label4, 
    #slide4:checked ~ #controls label.c-label5, 
    #slide5:checked ~ #controls label.c-label1 {
    float: right;
    display: block;
    }

I want the last execution of the FOR loop to append a '1' to the end of 'label', so that the CSS selector points back to the first element "c-label1". This is being used to build a pure CSS slider that changes the slides using radio buttons and needs to loop the slides back to the beginning once it gets to the end. I need the code to automatically update whenever there is a new database entry saved.

Can anyone help me clean up the code so it works?

Thank you SO much in advance.

In your for loop condition you have

$c < $slidecount

It means that the same condition in your loop body is also met, so your code to generate c-label1 will never be executed.

Try changing

$c < $slidecount 

to

($c < ($slidecount-1))

This is happening because you are using $c < $slidecount in your statement but your $c value starts from 0 so it will never happen to match your slidecount and won't be false. You should also change your round bracket ()

A quick solution could be to add 1 to your $c variable. This should work

(($c+1) < $slidecount ? ($c + 2) . ', ' : '1');

It is how you are using ( and ) . try this:

echo '#slide' . ($c + 1) . ':checked ~ #controls label.c-label' . ($c < $slidecount ? $c + 2 . ', ': '1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM