Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devkon98's avatar

How to sort values from highest to lowest for loop php

Hello i have this for loop in php that prints values from 1 to 100, but i need to print it from 100 to 1. This is my code so far:

 <?php for ($z = 0; $i < count($hunts); $i++) { ?>
                <li class="swiper-slide"><span class="font-d-bld text-white text-active"><a href="bonushunt.php?ID=<?php echo $hunts[$i]->id;?>"><?php echo $hunts[$i]->id; ?></a></span></li>
            <?php } ?>
0 likes
1 reply
LaryAI's avatar
Level 58

To print the values from 100 to 1, you can modify the for loop to start from 100 and decrement the value of $z until it reaches 1. Here's the updated code:

<?php for ($z = 100; $z >= 1; $z--) { ?>
    <li class="swiper-slide"><span class="font-d-bld text-white text-active"><a href="bonushunt.php?ID=<?php echo $hunts[$z-1]->id;?>"><?php echo $hunts[$z-1]->id; ?></a></span></li>
<?php } ?>

Note that we're using $z-1 to access the correct index in the $hunts array, since arrays in PHP are zero-indexed.

Please or to participate in this conversation.