Jeff Thomas
Jeff Thomas

Reputation: 4816

get every x numbers between two values

Is it possible to get every number divisible by 25000 between 2 values in php. For example, I am given the Min price of 191000 and the Max price of 432000. I know that I can do this using range() if I have a predefined array of the values but I am sure there is a better way to do it. Basically so the values returned are :

191000
200000
225000
...
425000
432000

Upvotes: 1

Views: 617

Answers (3)

SubjectCurio
SubjectCurio

Reputation: 4872

Rather than looping through 100,000's of times, you could combine a for loop with some rounding

$arr = [];
for($i = 191000; $i <= 432000; $i++) {
    $i = ceil($i / 25000) * 25000;
    if ($i > 432000) {
        break;
    }
    $arr[] = $i;
}

Upvotes: 1

Sam
Sam

Reputation: 20486

You can use a for loop (or @mschuett uses a foreach on a range()) and then the modulus operator (%) to see if the number is divisible by 25,000:

$numbers = array();
for($i = $min; $i <= $max; $i++) {
    if($i % $divisible === 0) $numbers[] = $i;
}
print_r($numbers);

Or you can find out the first number divisible by 25,000 and then use a for loop that increments by 25,000:

$base = ceil($min / $divisible) * $divisible;
for($i = $base; $i <= $max; $i += $divisible) {
    $numbers[] = $i;
}
print_r($numbers);

Obviously in both examples $min, $max, and $divisible need to be defined. Both examples output:

Array
(
    [0] => 200000
    [1] => 225000
    [2] => 250000
    ...
    [9] => 425000
)

Upvotes: 4

michael.schuett
michael.schuett

Reputation: 4741

foreach(range(min, max) as $num){
    if($num % 25000 == 0){
        echo $num;
    }
}

Upvotes: 1

Related Questions