user3302488
user3302488

Reputation: 15

How to do mathematical calculation inside foreach loop?

I am new to php, I have a function to do sum. Heres below:

<?php
class math {
    public function add($data) { // add("1,2,3") separated by comma
        $data=explode(",", $data);
        foreach($data as $val){
            echo $val +=$val;
        }
        return $val;
    }

}
$class_math = new math;
echo $class_math->add("1,2,3,4");
?>

But this should give result =10, but it is giving result 8, where's the error ?

Upvotes: 1

Views: 2154

Answers (2)

John Conde
John Conde

Reputation: 219934

You're overwriting the value of $val in your loop.

public function add($data) { // add("1,2,3") separated by comma
    $data=explode(",", $data);
    $total = 0;
    foreach($data as $val){
        echo $total+=$val;
    }
    return $total;
}

FYI, an easier way to do this might be to use array_sum():

public function add($data) { // add("1,2,3") separated by comma
    $data=explode(",", $data);
    return array_sum($data);
}

Upvotes: 5

Halcyon
Halcyon

Reputation: 57721

You have a duplicate variable name: $val

public function add($data) { // add("1,2,3") separated by comma
    $collect = 0;
    $data=explode(",", $data);
    foreach($data as $val){
        $collect += $val;
    }
    return $collect;
}

In the last iteration $val is 4, so it does 4+4=8

Upvotes: 4

Related Questions