PHP Looping in an array to find how many elements can I sum without surpassing an amount
Solution:
it's better to use while
statement and 1 loop would be enough.
$source = array(35, 20 ,15, 14, 9, 5);
$i = 0 ;
$counter = 0;
$len = count($source);
while( $i < $len && $source[$i] > 14 ) {
if($source[$i] >= 30 ) {
unset($source[$i]);
$counter++;
} else if ($source[$i] < 30) {
if($i + 1 < $len) {
$sum = $source[$i] + $source[$i+1] ;
unset($source[$i]);
unset($source[$i + 1]);
$i++;
$counter += 2;
}
}
$i++ ;
}
var_dump($source);
var_dump( $counter );
Answer
Solution:
So i've come up with a different solution compared to @Nazeri. We check to see if the total weight is bigger or smaller than the amount specified. If bigger, we remove the biggest element from the total weight, unset it and increment the counter. If smaller we unset the whole array and increment the counter.
Feel free to leave any opinions or error found in the code.
if($arrayItemSize > 1)
{
for($x = 0; $x < $arrayItemSize - 1; $x++)
{
if($itemTotalWeight <= 30)
{
unset($sortArrayItem);
$counter++;
break;
}
else
{
$itemTotalWeight = $itemTotalWeight - $sortArrayItem[$x];
unset($sortArrayItem[$x]);
$counter++;
}
}
}
else {
$counter++;
}
Source