Search code examples
phpnumbersclosest

PHP - get closest number given a certain number?


I'm modifying one of OpenCart's product filters to filter products in/out by price. What I do is get all products belonging to a certain category and extract their prices to put them in a slider, but this is not elegant or 'professional' at all, and I would like to code a proper solution.

Let's say I have the following prices: 125, 270, 517, 1680 and 14790. What I would like to do (ideally) is get the highest number (14790 in this short example) and, from it, get something like '15000', so I can divide that between a given factor (like 100) and put that into a slider.

Is there a PHP function to do this kind of calculation?


Solution

  • Get the max number, then round it up to the nearest thousand?

    <?php
    
    $largest = max(125, 270, 517, 1680, 14790);
    
    $nearest = ceil($largest / 1000) * 1000;