Search code examples
phpnumbersdivide

Divide number into equal parts


not sure how to describe this.. but here goes..

I have a number stored in a variable $a = 4520 This number can and will change.

I want to divide this by variable $b which is currently 50

so $a \ $b

4520 \ 50 = 90.4

What I want to do is return the divided value for each of the 90.4 sections in to an array $c

So $c contains 50,100,150,200 etc upto the last value.

The aim is to have an array of nearly equal parts of 4520 when divided by 50. The last entry will have any remainder.

Any way to do this ? Sorry it's not very clear.. I'm finding it hard to explain.


Solution

  • //Your starting values
    $a = 4520;
    $b = 50;
    
    /**
     * Array and FOR loop where you add the
     * second value each time to an array,
     * until the second value exceeds the
     * first value
     */
    $c = array();
    for($n = $b; $n <= $a; $n += $b) {
        array_push($c,$n);
    }
    
    /**
     * If the new final value is less than
     * (not equal to) the original number,
     * add the original number to the array
     */
    if($n > $a) array_push($c, $a);
    
    /**
     * If the new running total is greater
     * than (and not equal to) the original
     * number, find the difference and add
     * it to the array
     */
    #if($n > $a) array_push($c, $n-a);
    
    //Print values
    echo '<pre>';
    print_r($c);
    

    EDIT: Added final value (not final remainder)