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

devkon98's avatar

Sort for loop values from highest to lowest php

Hello i have this for loop in php that prints values x amount of number but i need to print it from highest to lowest This is my code so far:

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

To sort the values from highest to lowest, you can use the arsort() function to sort the $hunts array in descending order based on the values. Then, you can loop through the sorted array using a foreach loop to print the values in the desired order. Here's the updated code:

<?php 
arsort($hunts); // sort the array in descending order based on values
foreach ($hunts as $hunt) { // loop through the sorted array
?>
    <li class="swiper-slide"><span class="font-d-bld text-white text-active"><a href="bonushunt.php?ID=<?php echo $hunt->id;?>"><?php echo $hunt->id; ?></a></span></li>
<?php 
} 
?>

Note: If you need to preserve the original keys of the array, you can use arsort($hunts, SORT_NUMERIC) instead.

Please or to participate in this conversation.