简体   繁体   中英

how do i sum two variables in for each loop or while or for loop

is that possible to sum variable static values in the while or for loop? i have code and working on it but it sum variables only one time?

Here My Code

session_start();

$length=count($_SESSION['product1']);   

$shipping2='280';
$shipping3='680';
$newshipping='0';
$newshipping1='0';
$i='0';

while($i= <$length)
{
$newshipping=$shipping2+$shipping3;
$newshipping1=$newshipping+$shipping2;
}

For Example I want like this

$shipping2='280'; should be sum with every result of $newshipping1

`$newshipping1`= $shipping2='280' + $shipping3='680' = `$newshipping1`=960 
 +  $shipping2='280'??

'$newshipping1`=960+ $shipping2=280+ $shipping2=280+ $shipping2=280 ..... 
 when ever new product1 enter it should be add  $shipping2=280 
 in the result of `$newshipping1`

I have completed my code here my final code

$length=count($_SESSION['product1']);   
$shipping2=280;
$shipping3=680;
$newshipping=0;
for($i=0; $i <$length; $i++) {
if($i == 1) { 
$newshipping = $shipping2+$shipping3; 
} else if($i <= 100) {
$newshipping = $newshipping+$shipping2;
}
}

Your logic seems a bit confusing, however you can sum several integers. If you are trying to figure out the final amount of several iterations you should:

$shipping_one = 680;
$shipping_two = 260;
$shipping_three = 0;
$finalShipping = array();

while($i= <$length)
{   
    $finalShipping[] = $shipping_one + $shipping_two + $shipping_three;
}

$finalTotal = array_sum($finalShipping);

If you can clarify your question, I can clarify my answer.

this will be ((680) + (4 * 280)) like you explained in your last comment.

$length = 1;
echo "Test with $length : ".getShippingTotal($length)." <br />";

$length = 2;
echo "Test with $length : ".getShippingTotal($length)." <br />";

$length = 3;
echo "Test with $length : ".getShippingTotal($length)." <br />";

$length = 4;
echo "Test with $length : ".getShippingTotal($length)." <br />";

$length = 5;
echo "Test with $length : ".getShippingTotal($length)." <br />";

function getShippingTotal($length) {

    $shipping2=280;
    $shipping3=680;
    $total = 0;

    for($i=0; $i < $length; $i++) {
      if($i == 0) { 
          $total += $shipping2+$shipping3; 
      } else {
          $total += $shipping2;
      }
    }
    return $total;
}

I have tested it and it gave me:

Test with 1 : 960 
Test with 2 : 1240 
Test with 3 : 1520 
Test with 4 : 1800 
Test with 5 : 2080 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM