logic – Sum values received from foreach loop php-ThrowExceptions

Exception or error:

I want to sum the values in my custom function, where the argument/parameter received is a variable from the foreach loop in another file.

Below is the code:

// $value is the looped variable from another function
function custom_function($value) {
  // simple logic
  $var = [];
  $var += $value;
  print_r($var);

  // using array logic
  $array = [];
  $array[] = $value;
  print_r($array);
}

The issue is, using any of the print_r I’m getting the output as:

Array
(
    [0] => 100
)
Array
(
    [0] => 200
)

What I need is 300, i.e. the sum of 100 + 200 the reason I suspect is the $value is the looped variable.

How to solve:

You can use a static variable to maintain the sum between function calls:

function custom_function($value) {
    static $var = 0;
    $var += $value;
    echo "$var\n";
}

custom_function(100);
custom_function(200);

Output:

100
300

Demo on 3v4l.org

Answer:

$a = array('10','20','30');
$result = array();
$temp = 0;
foreach($a as $v)
{
  $temp  = $v+$temp; 
  array_push($result,$temp);

}
echo end($result);
echo '<br>';
print_r($result);

I am thinking $a is an array of which values are passed. Try doing this if you dont want to change much of the logic just create 2 temporary variables

Answer:

You can use array_sum to calculate the sum of array values

function custom_function($value) {
  // simple logic
  $var = [];
  $var += $value;
  print_r($var);
  print_r(array_sum($var));
}

 $array = array('100','200');
 $res= array(); //declare a new array 
 foreach($array as $val)
  {
    array_push($res,$val);  // push each element to newly created array
  }
 custom_function($res); //call custom function to calculate the sum of array elements

Leave a Reply

Your email address will not be published. Required fields are marked *