Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading