The thing i want to do is :
$numbertodivise = 500;
500 / 3 = 166,66
I want to divise the number in the most equitable part and the last part to add the difference , exemple :
500 / 3 will give me :
$result1 = 166
$result2 = 166
$result3 = 168
i want the code for every division how is the best way to do that ?
Here I have extracted the remainder of the numbertodivise
e.g. 2 if modulus with 3, and later I divided and extracted the integer part of the division so that I can add the remainder into last divided number i.e. 166 in this case.
<?php
$numbertodivise = 500;
$no = 3;
$intnumber = intval($numbertodivise / $no);
$rem = $numbertodivise % $no;
$array = [];
for($i=1;$i<=$no;$i++) {
if($i==$no) {
$array[] = $intnumber + $rem;
} else {
$array[] = $intnumber;
}
}
echo "<pre>";
print_r($array);
?>
Output will look like this:
Array
(
[0] => 166
[1] => 166
[2] => 168
)
For making variables as you mentioned use:
<?php list($result1, $result2, $result3) = $array; ?>
For PHP 7, you can use this function (check comment for <7):
function get_results($val, $qt){
$division = intdiv($val, $qt); // PHP <7: $division = ($val - ($val % $qt)) / $qt;
$ret = array_fill(0, $qt, $division); // fill array with $qt equal values
if($division != $val / $qt){ // if not whole division, add remaning to lsat element
$ret[count($ret)-1] = $ret[0] + ($val % $qt);
}return $ret;
}
Use it like this:
print_r(get_results(500, 3));
And the output will be:
Array
(
[0] => 166
[1] => 166
[2] => 168
)
This is a way to do it using intval()
and the modulo operator %
:
<?php
$divide = 500;
$divideWith = 3;
for($i=0; $i < $divideWith; $i++)
{
echo "This is result".($i+1).": ";
// If $i is not on the last iteration
if($i != $divideWith-1)
// intval() returns integer part without rounding. It
// floors the value inside the parenthesese.
echo intval($divide/$divideWith).'<br/>';
else
// ($divide % $divideWidth) will return the remainder of
// division between $divide and $divideWidth.
// The remainder is always an int value.
echo (int($divide/$divideWith) + ($divide % $divideWith)).'<br/>';
}
?>
The result of which will be:
This is result1: 166
This is result2: 166
This is result3: 168
A method that does not loop and uses basic PHP functions.
I use array_fill to fill the array with the floor of the calculation.
Then I add the remainder to the last item in the array.
$number = 500;
$divise =3;
$arr = array_fill(0, $divise, floor($number/$divise));
$arr[count($arr)-1] += $number-(floor($number/$divise)*$divise);
// Above line can also be . $arr[count($arr)-1] += $number-$arr[0]*$divise;
Var_dump($arr);