PHP Making a variable increment based on another variable's value without having too much code?

Issue

i’m trying to increase a variable value depending on the other variable value for example:

i have a variable called $totalhousesleft…

i want to set a price depending on how many $totalhousesleft i have…

everytime the totalhousesleft is down by 10, i want to increase the variable $currentprice by 1.

the starting value of $totalhouses left is 8000 and every time it goes down by 10, i set the $currentprice +1… the starting value of current price is 9…

something like:

If ($totalhousesleft >= 8000) {$currentprice = 9;  $sellingprice = 8;}
If ($totalhousesleft >= 7990) {$currentprice = 10;  $sellingprice = 9;}
If ($totalhousesleft >= 7980) {$currentprice = 11;  $sellingprice = 10;}
If ($totalhousesleft >= 7970) {$currentprice = 12;  $sellingprice = 11;}

ALL THE WAY DOWN UNTIL HOUSES LEFT IS 1. If someone can please show me a loop or a shorter code i would really appreciate it!

Solution

A for or while loop could be used for this. I’d use for:

$iteration = 0;
for($x = 8000; $x > 0; $x = $x - 10){  
    if(empty($iteration)) {
        $iteration = $x/1000;
    }
    if ($totalhousesleft >= $x) { 
        $currentprice = $iteration;
        $sellingprice = $currentprice + 1;
        break;
    }
    $iteration++;
}
if(empty($currentprice)){
    $currentprice =  $iteration;
    $sellingprice = $currentprice + 1;
}

This iterates over until a match is found then breaks out of the looping. The prices are based on the iteration it is in.

Demo link: https://3v4l.org/Mm432 (updated for edge cases 0-9)

Answered By – user3783243

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published