I need to fill an array with numbers, a few examples:
nbreParChargement = 4; For 10
Expected output: $niveaux = array(4,4,2);
4+4+2 = 10
nbreParChargement = 6; For 14
Expected output: $niveaux = array(6,6,2);
6+6+2 = 14
nbreParChargement = 16; For 13
Expected output: $niveaux = array(13);
13 = 13
nbreParChargement = 4; For 30
Expected output: $niveaux = array(4,4,4,4,4,4,4,2);
4+4+4+4+4+4+4+2 = 30
I tried to resolve this but I don't know the perfect solution:
function chargement($nbre, $nbreParChargement) {
$niveaux = array();
for($i=0; $i<=$nbre; $i++){
$niveaux[$i] = $i + $nbreParChargement;
}
}
Another implementation, with two lines of code, for php >= 5.6:
function chargement($nbre, $nbreParChargement){
$niveaux = array_fill(0, floor($nbre/$nbreParChargement), $nbreParChargement);
$niveaux[] = $nbre - array_sum($niveaux);
return $niveaux;
}
var_dump(chargement(10, 4));
var_dump(chargement(14, 6));
var_dump(chargement(13, 16));
var_dump(chargement(30, 4));
array_fill
fills an array with $nbre/$nbreParChargement
entries with $nbreParChargement
's value. The last value are the difference between $nbre
and the sum of the other elements, given by $nbreParChargement * floor($nbre/$nbreParChargement)
, that will be always > 0.
Demo.
This work only for php >= 5.6 because array_fill
accepts 0
as num
only from that version. Previously, num
was required to be greater than zero.
So, for any version of php:
function chargement($nbre, $nbreParChargement){
$niveaux = array();
if ($n = floor($nbre/$nbreParChargement)) {
$niveaux = array_fill(0, $n, $nbreParChargement);
}
$niveaux[] = $nbre - array_sum($niveaux);
return $niveaux;
}
Demo.