Chinmay235
Chinmay235

Reputation: 3414

PHP: getting calculation issue in the for loop

Sorry for this silly question. I want to spend 25 credits of my available credit is 30(10,10,10). But in my below sample code, the final amount is getting minus(-) 5 value instead of 5. Could you please check my code, actualy output and my expected result:

Code:

<?php
$content_credit = 25;
$data = array(10,10,10);
$used_credit = 0;
for($i=0; $i<count($data); $i++){
    if($content_credit > $used_credit){
        $used_credit += $data[$i];
        echo "Point: " . $data[$i];
        echo " Used: " . $used_credit;
        echo " Remaining: " . ($content_credit - $used_credit);
    }
    echo "<br>";
}

Actual Result:

Point: 10 Used: 10 Remaining: 15
Point: 10 Used: 20 Remaining: 5
Point: 10 Used: 30 Remaining: -5

Expected Result:

Point: 10 Used: 10 Remaining: 15
Point: 10 Used: 20 Remaining: 5
Point: 10 Used: 25 Remaining: 5

Upvotes: 0

Views: 68

Answers (3)

Cray
Cray

Reputation: 2850

You are probably looking for something like:

<?php
$content_credit = 25;
$data = array(10,10,10);
$total = array_sum($data);
$used_credit = 0;
for($i=0; $i<count($data); $i++){
    if($content_credit > $used_credit){
        $used_credit += $data[$i];
        echo "Point: " . $data[$i];
        echo " Used: " . $used_credit;
        $remaining = $used_credit > $content_credit ? $total - $content_credit :  $total - $used_credit;
        echo " Remaining: " . $remaining;
    }
    echo "<br>";
}

You need to know how much credit you have in total to calculate the remainings.

To get the amount of actual credit used it is enough to know which value is smaller between $used_credit and $content_credit. So you can use min() to get the value.

echo " Used: " . min($used_credit, $content_credit);

Similarly the $remaining can be replaced with max() value of the ternary operator results or a simple calculation $total - $actual_used.

echo " Remaining: " . max($total - $content_credit,  $total - $used_credit);

Upvotes: 1

Vipin Kumar Soni
Vipin Kumar Soni

Reputation: 834

<?php
$credit_to_spend = 25;
$available_credit = array(10,10,10);
$used_credit = 0;

for( $i=0; $i<count($available_credit); $i++ ){
    if( $credit_to_spend > $used_credit ){

        $required = ($credit_to_spend - $used_credit);
        $used_credit += ($required < $available_credit[$i]) ? $required : $available_credit[$i];
        $remaining = (($required < $available_credit[$i]) ? ($available_credit[$i] - $required): ($credit_to_spend - $used_credit));

        echo "Point: " . $available_credit[$i] 
        . " Used: " . $used_credit 
        . " Remaining: " . $remaining;
    }
    echo "<br>";
}

Upvotes: 1

Haris
Haris

Reputation: 368

$content_credit in first iteration becomes 10, then in second it become 20 due to the +=.

Hence 25 - 10 - 20 = -5

Upvotes: 2

Related Questions