Search code examples
phpcalculus

What is the best solution for filling limited variables in PHP


Let's say I have 3 variables

$a;
$b;

$c = 30;

What I wish to do here is that I have to divide $c and put it in the first 2 variables which can be easily done by doing.

$a = $c / 2;
$b = $c / 2;

However what if in $b there is a maximum value limit of 10 and $a is limitless.
In this case the values have to be.

$a = 20;
$b = 10;

What would be the best solution for this?


Solution

  • If B has a limit, then you would need to calculate B first. Then work out the difference between C & B and set A as the answer.

    <?php
    
    $a;
    $b;
    
    $c = 100;
    
    
    $b = min(10, $c / 2);
    $a = ($c - $b);
    
    echo "A: " . $a;
    echo "B: " . $b;
    ?>