1

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?

2
  • I think this question is better post to codereview.stackexchange.com, anyway set max/min to input will solve one of your problem Commented Jan 24, 2022 at 14:10
  • 1
    "So basically increasing by 200 every tenth" You've just described the algorithm for your solution. Write that sentence in code. Commented Jan 24, 2022 at 14:13

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.