Daniel Mordi
Daniel Mordi

Reputation: 49

How can I subtract a value gotten from the loop

This is my code

// $res[] has two values(75000, 30000)
// $_SESSION['requestedAmt'] = 35000
while ($row = $queryWithdrawalTable->fetch_assoc()) {
    $res[] = $row['profit_amt'];
    foreach ($res as $amt) {
        if ($_SESSION['requestedAmt'] > $amt) {
            $calc = $_SESSION['requestedAmt'] - $amt;
        } else {
            $calc = $amt - $_SESSION['requestedAmt'];
        }
    }
    echo $calc; // outputs 5000 40000 
}

What I actually want to achieve is

$a[] = (1500, 3000);
$b = 2500;

while(fetch the data) {
  $res = $a - $b;
}
// output = 2000

I want the value in $b to subtract the first value in $a(1500) and use result gotten from the first calculation to subtract from the second value(3000). please note I'm new to programming so any suggestion will be accepted thanks guys.

I want to be able to assign a single user to pay multiple users. for example user1 has to pay $100 to user2($25), user3($50) and user4($25). I have user1 money in $_SESSION['requestedAmt'] while the other users in $row['profit_amt']

Upvotes: 0

Views: 409

Answers (1)

catcon
catcon

Reputation: 1363

You are almost there, you only perform the calculation after you have all the value inside the $res array

while ($row = $queryWithdrawalTable->fetch_assoc()) {
    $res[] = $row['profit_amt'];
}

$calc = $_SESSION['requestedAmt'];
foreach ($res as $amt) {
    if ($_SESSION['requestedAmt'] > $amt) {
         $calc = $calc - $amt;
    } else {
         $calc = $amt - $calc;
    }
}

echo $calc;

Or you don't need the $res array at all, perform the calculation while fetching the rows:

$cals = $_SESSION['requestedAmt'];
while ($row = $queryWithdrawalTable->fetch_assoc()) {
    if ($_SESSION['requestedAmt'] > $row['profit_amt']) {
         $calc = $calc - $amt;
    } else {
         $calc = $amt - $calc;
    }
}

Upvotes: 1

Related Questions