Skip to content
Advertisement

PHP Variable value based on user input

I’m building an application to help customer calculate various product prices.

Right now I’m building a feature where user enters a single number to the application and submits a form. Based on that number, I would like to define another variables value.

What I’d like to achieve

If user input is number between 1-10, set variable number to 200.

If user input is number between 11-20, set variable number to 400.

If user input is number between 21-30, set variable number to 600.

If user input is number between 31-40, set variable number to 800.

If user input is number between 41-50, set variable number to 1000.

And so on… So basically increasing by 200 every tenth. Of course, I could do something like this:

$userInput = 11;
$result;

if($userInput => 1 && $userInput =< 10)
$result = 200;

if($userInput => 11 && $userInput =< 20)
$result = 400;

if($userInput => 21 && $userInput =< 30)
$result = 600;

But it isn’t really a great solution, because it takes lot of code and if user sets number out of the determined range it doesn’t work..

How can I implement this with as little amount of code as possible?

Advertisement

Answer

If I have the math right, you just need to divide the number by 10, and use ceil to round the fraction up. From there, multiply it by 200;

function getVariable($num) {
    $divisor = ceil($num / 10);
    return $divisor * 200;
}


echo getVariable(1)."n"; // 200
echo getVariable(6)."n"; // 200
echo getVariable(13)."n"; // 400
echo getVariable(27)."n"; // 600
echo getVariable(48)."n"; // 1000
echo getVariable(50)."n"; // 1000
echo getVariable(88)."n"; // 1800
echo getVariable(100)."n"; // 2000 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement