add numbers in an array with PHP - php

I want all of the elements in the array to be added together, but this doesn't seem to be working.
<?php
function mimic_array_sum($array) {
foreach($array as $total) {
$total = $total + $total;
}
return $total;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>

$total = $total + $total --> well, there's your problem...
The $total variable gets overwritten on each loop through the array.
Assign a separate variable for each number in the array, like so:
function mimic_array_sum($array) {
$total = 0;
foreach($array as $number) {
$total = $total + $number;
}
return $total;
}
$var = array(1,2,3,4,5);
echo mimic_array_sum($var);
Although the point of this is not clear to me... You might as well use the php-function array_sum...
$var = array(1,2,3,4,5);
echo array_sum($var);

$var = array(1,2,3,4,5);
$total = array_reduce(
$var,
function($sum, $value) {
return $sum + $value;
}
);
though why not simply use array_sum()?

You can use array_sum — Calculate the sum of values in an array
$var = array(1,2,3,4,5);
$total = array_sum($var);
echo $total;

<?php
function mimic_array_sum($array) {
$total = 0;
foreach($array as $elem) {
$total += is_numeric($elem) ? $elem : 0;
}
return $total;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>

<?php
$a = array(1,2,3,4,5);
echo "sum is:".array_sum($a);
?>
See Manual

Please try following, you have to take separate variable to do so. Or else you can use array_sum()
function mimic_array_sum($array) {
$test = 0;
foreach($array as $total) {
$test = intval($test) + intval($total);
}
return $test;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;
?>

Related

array_sum return raw numbers without sum - php

I am using Array_sum like this
<?php
$totalAmount = $db->prepare('SELECT
a.proId, a.userId,
b.id, b.pPrice
FROM purchaseshistory AS a
INNER JOIN products AS b ON(a.proId=b.id)
WHERE a.userId=?');
$totalAmount->bind_param('i', $cus['cId']);
$totalAmount->execute();
$totalAmount->bind_result($proId, $userId, $id, $pPrice);
$totalAmount->store_result();
while ($totalAmount->fetch()) {
$sum = 0;
$amount = $pPrice;
$amount = is_array($amount) ? $amount : array($amount);
foreach ($amount as $item => $value) {
$sum += $value;
}
print $sum;
}
?>
and also tried to make it like this
while ($totalAmount->fetch()) {
$amount = array($pPrice);
print array_sum($amount) ;
}
same results I get the numbers like 200150200
$amount = [];
while ($totalAmount->fetch()) {
$amount[] = $pPrice;
}
echo array_sum($amount);
You're not adding elements to an array.. the code above is and should work as you expect
Update for older PHP versions
$amount = array();
while ($totalAmount->fetch()) {
$amount[] = $pPrice;
}
echo array_sum($amount);
Another alternative (without using array_sum()):-
$sum = 0;
while ($totalAmount->fetch()) {
$sum += $pPrice;
}
echo $sum;

Pair the elements in an array by two's then find the difference and sum

Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array

String as calculation in php

I've got field in my database which contain strings like 21;48;33;22;31. Then I'd like to convert it to mathematical calculation 21+48+33+22+31.
$points = "21;48;33;22;31";
$points = str_replace(";","+",$points );
$points = preg_replace('/[^0-9\+\-\*\/\s]+/', '', $points);
echo $points;
But that simply does not work. I've got the same string "21+48+33+22+31" instead of the sum.
$points = "21;48;33;22;31";
$points = explode(';',$points );
$points = array_sum($points);
echo $points;
$points = "21;48;33;22;31";
$arr = explode(";", $points);
$points = 0;
foreach($arr as $key => $rows){
$points += $rows[$key];
}
echo $points;
Try above code it will give you proper result.
or you can try it also:
$points = "21;48;33;22;31";
$arr = explode(";", $points);
echo $points = array_sum($arr);
The easiest way is to explode the string.
Then you can iterate with foreach over the resulting array and calculate them.
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = 0;
forearch($points as $point) {
$calc += $point;
}
Or your can use array_sum:
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = array_sum($points);
Something like that. Perhaps there are some shorter ways.
$string = "21;48;33;22;31";
$string = explode(";" , "21;48;33;22;31");
$point = 0;
foreach($string as $num)
{ // by using (int) you can convert string to int.
$point = (int)$num + $point;
}
print($point);
// output
155
explode it then loop for sum...
<?php
$total = 0; // for getting the total
$points = "21;48;33;22;31";
$points = explode(';',$points);
for($i=0;$i<count($points);$i++){
$total+= $points[$i];
}
echo $total;
?>
<?php
eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';');
echo $sum;

Sum of Array in PHP

Looking to calculate average of $data array. I need to first find the sum of the values in the array. Here's what I have but it doesn't seem to work.
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
return $sum;
}
$count = count($data);
$average = $sum / $count;
echo "Average is $average <br />";
Try this:
$total = array_sum($data);
$average = $total / count($data);
Or, if you like one-liners:
$average = array_sum($data) / count($data);
remove the return
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
}
$count = count($data);
$average = $sum / $count;
echo "Average is $average <br />";
The reason it's failing is that you shouldn't have the return statement. return is only used for returning from functions.
That said, you can just use array_sum() instead.

calculate the arithmetic elements of php array?

this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?
2 times the first entry minus the whole sum - looks pretty quick.
echo (2 * reset($arr)) - array_sum($arr);
Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # -13
To preserve the array, change the calculation a little:
echo $arr[0]*2 - array_sum($arr); # -13
And we're glad you didn't ask for eval:
echo eval('return '.implode('-', $arr).';'); # -13
However the best suggestion I can give is that you encapsulate the logic into a class and overload the array with it. So that the object than can provide a method for the calculation (Demo):
class Operands extends ArrayObject
{
public function operate($sign)
{
$sign = max(-1, min(1, $sign.'1'));
$arr = $this->getArrayCopy ();
return $arr[0]*(1-$sign) + $sign*array_sum($arr);
}
public function __invoke($sign) {
return $this->operate($sign);
}
}
$arr = new Operands($arr);
echo $arr('-'), ', ' , $arr('+');
<?php echo eval(implode("-", $arr)); ?>
Try this:
$arr = array(1,2,3,4,5);
// load the first number to subtract
$result = $arr[0];
$i = 1;
foreach($arr as $item)
{
if ($i !=1) // skip the first one
$result -= $item;
$i++;
}
echo $result;
?>
This?
<?php
foreach ($arr as $val)
{
$calc -= $val;
}
echo $calc;
?>
Like #mOrSa, but more readable:
<?php
$arr = array(1, 2, 3, 4, 5);
// load the first number to subtract
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++)
{
$result -= $arr[i];
}
echo $result;
?>

Categories