Count array values in a loop and then add together - php

I'm struggling with this for a while now and getting more important at the moment.
Lets say we have a array with the values
Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
)
when i loop this array in a foreach loop i want the first result 11 second result 36 (11 + 25) 3rd result 38 (11 + 25 + 2) 4rd result 45 (11 + 25 + 2 +7) etc....
this way i get cumulative results
This is what i tried so far:
<?php
foreach(array_slice(weeks($start_week), 0, 26) as $week):
$gewasregistratie["gezette_vruchten_cumulatief"][$week] = $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week] + $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week-1];
$gewasregistratie["gezette_vruchten_cumulatief"][$week] += $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week];
endforeach;
foreach(array_slice(weeks($start_week), 0, 26) as $week):
echo "<td week='".$week."' class='part1'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
foreach(array_slice(weeks($start_week), 26, 51) as $week):
echo "<td week='".$week."' class='part2'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
?>
Can someone help me in the right direction ?

Simple like boiling a egg. Try this code
$test = array(11,25,2,7);
$count = 0;
foreach($test as $i=>$k)
{
$count +=$k;
echo $count." ";
}
Output:
11 36 38 45
Suggestion: you can store output in another array also.

Try this:
$a = array(11,25,2,7);
$c = 0;
foreach($a as $k=>$v){
$c += $v;
$b[] = $c;
}
print_r($b);
you will get result in array like below :
Array ( [0] => 11 [1] => 36 [2] => 38 [3] => 45 )

The simplest way
$original = array(23, 18, 5, 8, 10, 16);
$total = array();
$runningSum = 0;
foreach ($original as $number) {
$runningSum += $number;
$total[] = $runningSum;
}
var_dump($total);

$array = array( 11, 25, 2, 7 );
$results = array();
foreach ($array AS $i => $v) {
if (empty($results)) {
$results[] = $v;
} else {
$results[] = $v + $results[$i - 1];
}
}
Something like this.

Try this code
$arr=Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$sum=0;
foreach($arr as $k=>$val)
{
echo "<br>".$sum+=$val;
}

Find below solution
$arr = array(11,25,2,7);
$sum =0;
foreach($arr as $val){
$sum +=$val;
echo $sum ."<br/>";
}

If you are looking to iterate over a single-dimensional array as your question was initially worded, array_map would be your most efficient method:
function cascade($n) {
static $current = 0;
return $current += (int) $n;
}
$test = array(11,25,2,7);
$result = array_map('cascade', $test);
/**
* You could also assign back to the original array like:
* $test = array_map('cascade', $test);
*/
If you are looking to do something in a multi-dimensional array, using array_walk would be the solution there. Would you like an example?

Try this.
$myArray = Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$total = 0;
for($i=1; $i <= count($myArray); $i++) {
$total += $myArray[$i];
echo $total . ", ";
$cumulativeArray[] = $total;
}
print_r($cumulativeArray);

Related

How to concatenate an array with a 'foreach' loop?

I have several arrays.
example:
$a = Array(
[0] => #ID_1
[1] => #ID_2
[2] => #ID_3
)
$b = Array(
[0] => ABC
[1] => cde
[2] => fgh
)
$c = Array(
[0] => 000
[1] => 111
[2] => 222
)
How to concatenate these data fields using any foreach, for, while loop?
Expected result:
$result = '#ID_1 ABC 000';
I try something like this:
$result = '';
foreach($a as $aa) {
$result .= $aa ." ";
foreach ($b as $bb) {
$result .= $bb ." ";
foreach($c as $cc) {
$result .= $cc .'<br>';
}
}
}
but the result did not meet expectations.
Can anyone advise how to use foreach to chain these arrays together? Thank you. Thank you very much.
If you need foreach loop then use next code:
$res = [];
foreach($a as $ind=>$val){
$res[$ind] = $val." ".$b[$ind]." ".$c[$ind];
}
Demo
You can do something like this.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
$arrayLength = count($arr1);
$i = 0;
$result = [];
while ($i < $arrayLength)
{
$result[] = $arr1[$i]." ".$arr2[$i]." ".$arr3[$i];
$i++;
}
foreach($result as $item){
echo $item."<br/>";
}
According to what you're asking, you want to join elements with the key 0 from all arrays, then with the key 1 and so on, so instead of doing a foreach loop you could use a for loop using the key:
<?php
$a = Array(
0 => "#ID_1",
1 => "#ID_2",
2 => "#ID_3",
);
$b = Array(
0 => "ABC",
1 => "cde",
2 => "fgh"
);
$c = Array(
0 => 000,
1 => 111,
2 => 222
);
$length = sizeof($a);
$output = '';
for($i = 0; $i<$length; $i++) {
$output .= $a[$i] . ' / ' . $b[$i] . ' / ' . $c[$i] . '<br>';
}
echo $output;
?>
Outputs:
#ID_1 / ABC / 0
#ID_2 / cde / 111
#ID_3 / fgh / 222
Way to do this using foreach, if number of elements in each array is same.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
foreach($arr1 as $k => $item) {
echo "$item {$arr2[$k]} {$arr3[$k]}<br>";
}
using for loop this way would give you your expected result
<?php
$a = Array(
0 => '#ID_1',
1 => '#ID_2',
2 => '#ID_3'
);
$b = Array(
0 => 'ABC',
1 => 'cde',
2 => 'fgh'
);
$c = Array(
0 => '000',
1 => '111',
2 => '222'
);
$arrlengtha = count($a);
$arrla = $arrlengtha - 2;
$arrlengthb = count($b);
$arrlb = $arrlengthb - 2;
$arrlengthc = count($c);
$arrlc = $arrlengthc - 2;
for($x = 0; $x < $arrla; $x++) {
echo $a[$x]." ";
}
for($x = 0; $x < $arrlb; $x++) {
echo $b[$x]." ";
}
for($x = 0; $x < $arrlc; $x++) {
echo $c[$x]." ";
}
?>

How to get the factorial value of each number in an array?

I am trying to get an factorial value of each item in array by using this method but this outputs only one value
can any body help me finding where i am doing wrong?
function mathh($arr, $fn){
for($i = 1; $i < sizeof($arr); $i++){
$arr2 = [];
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value){
$x = 1;
return $x = $value * $x;
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
You're going to need a little recursion so in order to do that you need to pass the lambda function into itself by reference:
function mathh($arr, $fn){
$arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
if(1 == $value) {
return 1;
} else {
return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
}
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I wanted to expand on this some since you're essentially (in this case) creating an array map. This could be handy if you're doing additional calculations in your function mathh() but if all you want to do is use the lambda function to create a new array with a range you could do this (utilizing the same lambda we've already created):
$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);
You will get the same output, because the range (1,5) of the mapped array is the same as your original array:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)

How do I count the sum of specified sum in $total

e.g. if I pass $total = 2 then it should calculate the sum of first
two arrays.
sub1 + sub2
**HERE IS MY CODE **
<?php
$num = 2;
$array = array();
$total = 2;
for($x=1;$x<=$num;$x++)
{
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$array[] = $result;
}
echo '<pre>'; print_r($array);
?>
try
<?php
$array = array();
$total = 2;
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$temp_array = array_slice($result, 0, $total);
$sum = array_sum($temp_array);
print_r($result);
echo "sum of $total array is : ".$sum;
Output would be like :
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
https://eval.in/539097
should do the trick. hope it helps :)
simply you can use for loop like this
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}

php dynamic number array add missing values defined by a range

I have looked and googled many times I found a few posts that are simular but I can not find the answer Im looking for so I hope you good people can help me.
I have a function that returns a simple number array. The array number values are dynamic and will change most frequently.
e.g.
array(12,19,23)
What I would like to do is take each number value in the array, compare it to a set range and return all the lower value numbers up to and including the value number in the array.
So if I do this:
$array = range(
(11,15),
(16,21),
(22,26)
);
The Desired output would be:
array(11,12,16,17,18,19,22,23)
But instead I get back all the numbers in all the ranges.
array(11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26)
What would be a simple solution to resolve this?
Try this code
$range = array(
array(11,15),
array(16,21),
array(22,26),
);
$array = array(12,19,23);
$result = array();
foreach($range as $key=>$value)
{
//$range1 =$range[$key];
$min = $range[$key][0];
$max = $range[$key][1];
for($i = $min;$i<=$max;$i++)
{
if($i <= $array[$key])
{
array_push($result,$i);
}
}
}
echo "<pre>";print_r($result);
Iterate over each element, find the the start and end values you need to include, and append them to the output array:
$a = array(12,19,23);
$b = array(
range(11,15),
range(16,21),
range(22,26)
);
$c = array();
foreach ($a as $k => $cap) {
$start = $b[$k][0];
$finish = min($b[$k][count($b[$k])-1], $cap);
for ($i = $start; $i <= $finish; $i++) {
$c[] = $i;
}
}
print_r($c);
prints
Array
(
[0] => 11
[1] => 12
[2] => 16
[3] => 17
[4] => 18
[5] => 19
[6] => 22
[7] => 23
)
My solution is probably not the most efficient, but here goes:
$numbers = array(12,19,23);
$ranges = array(
array(11,15),
array(16,21),
array(22,26)
);
$output = array();
// Loop through each of the numbers and ranges:
foreach($numbers as $num) {
foreach($ranges as $r) {
if ($num >= $r[0] && $num <= $r[1]) {
// This is the correct range
// Array merge to append elements
$output = array_merge($output, range($r[0], $num));
break;
}
}
}
// Sort the numbers if you wish
sort($output, \SORT_NUMERIC);
print_r($output);
Produces:
Array
(
[0] => 11
[1] => 12
[2] => 16
[3] => 17
[4] => 18
[5] => 19
[6] => 22
[7] => 23
)

represent value of array products in another array

i have an array {
$e = Array ( [0] => 13 [1] => 11 [2] => 2 ) Array ( [989.32] => 13 [77] => 11 [0.99] =>2 );
and i want to multiply each key by their values respectively and use the values to create another array. Anyone know how?
i've tried:
foreach($e as $y=>$z)
{$x= $y * $z;
$p=array();
array_push($p,$x);}
print_r($p);
but i got:
Array ( [0] => 1.98 )
One little change in your code:
$p=array();
foreach($e as $y=>$z)
{
$x= $y * $z;
array_push($p,$x);
}
print_r($p);
Try this :
$p=array();
foreach($e as $y=>$z){
$x= $y * $z;
array_push($p,$x);
}
print_r($p);
Put your $p=array(); out side the loop
I assume your array was multidimensional array. so try like this
$e = Array(Array ( "0" => 13 , "1" => 11 , "2" => 2 ), Array ( "989.32" => 13 , "77" => 11 , "0.99" => 2 ));
$result = array();
$i=0;
foreach($e as $values)
{
foreach($values as $key=>$value)
{
$result[$i]= $key * $value ;
$i++;
}
}
print_r($result);
Demo
Hope you will understand why:
<?php
$e = array(...);
$p = array();
foreach ($e as $y => $z) {
$x = $y * $z;
array_push($p, $x);
}
So as you can see, in your code, you overwrite $p each time so that you get the last multiplication 0.99 * 2 = 1.98

Categories