Numeric array: add value of previous element to current element - php

For each element in the array, I need to add value of previous element to it's current element. Example:
Array
(
[0] => 460
[1] => 25
[2] => 25
[3] => 25
[4] => 25
[5] => 25
[6] => 25
)
How can I get like following:
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)
Any ideas?

Here's a quicker solution compared to the rest:
foreach ($a as $i => $val) {
// make sure the current item is not the first one.
// because the first one is the base number
if ($i > 0) {
// Update current $i (INDEX) by
// adding the previous value ($a[$i -1]) with the current value ($val)
$a[$i] = $a[$i - 1] + $val;
}
}
As 0 is the first value, we can't increment before it :) hence the if statement
And here is a demo: Example
It doesn't matter about what looping method you use, it's how you apply it. Look, here's the exact same thing done in a for loop:
for($i = 0; $i < count($a); $i++) {
if($i > 0) {
$a[$i] = $a[$i - 1] + $a[$i];
}
}
It all comes down to the preference of the coder using it.
Both of those loops return the correct data:
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)

Like this?
$source = array(460, 25, 25, 25, 25, 25, 25);
$result = array();
$last = 0;
foreach($source as $s){
$last = $result[] = $s+$last;
}

$previous = 0;
foreach ($a as $key => &$value)
$previous = $value = $previous + $value;
or
$sum = 0;
foreach ($a as $key => &$value)
{
$sum += $value;
$value = $sum;
}

Get the value of the previous index (do check if index > 0), and add it to the current value.
$values = array(
460,
25,
25,
25,
25,
25,
25
);
foreach($values as $key => &$value){
if($key > 0){
$prev_value = $values[$key-1];
$value += $prev_value;
}
}
echo print_r($values);

$array1 = (460, 25, 25, 25, 25, 25, 25);
function calculateAdjecentSum($array1)
{
$array2 = array();
$pointer = 0;
foreach ($array1 as $number) {
$sum = $pointer + $number;
$array2[] = $sum;
$pointer = $sum;
}
return $array2;
}

It's enough to use for loop:
<?php
$array = array
(
0 => 460,
1 => 25,
2 => 25,
3 => 25,
4 => 25,
5 => 25,
6 => 25,
);
for ($i=1, $c = count($array); $i<$c; ++$i) {
$array[$i] += $array[$i-1];
}
var_dump($array);
I have no idea why all other answers use foreach loop in this case as for in my opinion is better to do that (no conditions, no temporary variables, no unset references from foreach).

You can do like this
<?php
$yourarray = array(460, 25, 25, 25, 25, 25, 25);
$l = 0;
foreach($yourarray as $b){
$l = $b+$l;
echo $last;
}
Outputs 460485510535560585610

Try this :
<?php
$array = array( 460, 25, 25, 25, 25, 25, 25);
$result = array();
for ($i=count($array);$i>0; $i--){
$result[($i-1)] = array_sum($array);
array_pop($array);
}
echo "<pre>";
ksort($result);
print_r($result);
?>
Output :
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)

Related

I want to make a key value pair of numeric array in PHP on the base of index

foreach($manualsArray as $manuls){
for($i=0;$i<=count($manuls);$i++){
if($i/2 == 0){
$manuls = 23;
print($manuls);
}
else{
$manualsArray= 98;
print($manualsArray);
}
print($manualsArray);
}
}
I want to create key value pairs according to index like 0 is key 1 is value 2 is key 3 is value and so on.
the sample input is write below
Array
(
[0] => Array
(
[0] => Faucet Centers
[1] => 6, 4, 13, 12, 7, 10, 14, 16, 8, 5, 9, 15, 11 in.
[2] => Flow Rate (GPM)
[3] => 1.2
[4] => Height
[5] => 5.875 in.
[6] => Max Deck Thickness
[7] => 2.25 in.
[8] => Spout Height
[9] => 3.625 in.
[10] => Spout Reach
[11] => 5 in.
)
)
You can achieve this by changing your loop to increment by 2 each time and take $i as the key and $i+1 as the value...
$output = [];
foreach($manualsArray as $manual){
$m = [];
for ( $i = 0; $i < count($manual); $i+=2 ) {
$m [$manual[$i]] = $manual[$i+1];
}
$output [] = $m;
}
print_r($output);
you can use array_chunk()
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
echo 'key: ' . $pair[0] . ' is value: '. $pair[1] . "<br>/n";
}
}
or if you want an associative array
$result_array = [];
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
$result_array[] = [$pair[0] => $pair[1]];
}
}
var_export($result_array);
https://www.php.net/manual/en/function.array-chunk.php
Use modulo for that:
<?php
$newarray = array();
foreach($yourarray[0] as $id => $val){
if($id % 2 == 0){
$last_index = $val;
}else{
$newarray[$last_index] = $val;
}
}
?>
I assume that your array is the one you have given, so it's 2-dimensional.
If not, use $yourarray instead of $yourarray[0].

array matching count one less than expected

$ar is a sock of pairs. $n is the number of items in $ar. I have to match each number in the array with another if any of them match, its a pair. I have to then return the count of matched items. I have done it below but the answer is one less than what it should be. Example
n:9
ar: 10 20 20 10 10 30 50 10 20
I get output 2 instead of 3.
function sockMerchant($n, $ar) {
$pair =0;
$j=0;
for($i=0; $i< count($ar); $i++)
{
for($j=$i+1; $j< count($ar); $j++)
{
if ( isset( $ar[$j]) && isset( $ar[$i])) {
if ($ar[$i]== $ar[$j])
{
unset($ar[$i]);
unset($ar[$j]);
$pair+=1;
$i=0;
break;
}
}
}
}
return count($ar);
}
Instead of what you are doing there is shortcut to achieve the same,
$temp = array_count_values($arr); // count number of occurences
echo count(array_filter($temp, function($value){ // filter in not greater than 1
return $value > 1;
}));
The above snippet will give you all the pairs which are not only once.
Here is an one more alternative for your snippet,
$temp = array_count_values($arr); // count number of occurences
$e = array_reduce($temp, function ($carry, $item) {
$carry += ($item > 1 ? intval($item / 2) : 0);
return $carry;
});
echo $e;die;
Working demo.
$ar = [10, 20, 20, 10, 10, 30, 50, 10, 20];
$pairIndex = [];
$count = 0;
foreach ($ar as $key => $item) {
// Start comparing from the next element
for ($i = ($key + 1); $i < count($ar); $i++) {
if ($item == $ar[$i] && !in_array($key, $pairIndex)) {
$pairIndex[] = $key;
$pairIndex[] = $i;
$count++;
}
}
}
echo "Pairs: " . $count;
This will give you the number of pairs.
$arr = array(10, 20, 20, 10, 10, 30, 50, 10, 20);
$counts = array_count_values($arr); // count number of occurences
array_walk($counts, function(&$x) {$x = intdiv($x, 2);}); //divide each element
//by 2 (integer division), so now you have pairs of each element
echo array_sum($counts); //sum the pairs
Using your initial array, it echoes 3.
simple example what happens to your array:
$ar = array(0, 10, 20, 30, 40, 50 , 60, 70, 80, 90);
$lnPointer = 2;
print_r($ar);
// Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [8] => 80 [9] => 90 )
echo "<HR>";
echo $ar[$lnPointer];
echo "<HR>";
unset( $ar[$lnPointer]);
print_r($ar);
// Array ( [0] => 0 [1] => 10 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [8] => 80 [9] => 90 )
echo "<HR>";
echo $ar[$lnPointer];
after unsetting you get an undefined index
If you want total matched pair count then you should return $pair. But you are returning count($ar) which can not be correct in all the possible scenarios. Check the below code with output and new set of data:
<?php
function sockMerchant($n, $ar) {
$pair =0;
$j=0;
for($i=0; $i< $n; $i++)
{
for($j=$i+1; $j< $n; $j++)
{
if ( isset( $ar[$j]) && isset( $ar[$i])) {
if ($ar[$i]== $ar[$j])
{
unset($ar[$j]);
unset($ar[$i]);
$pair+=1;
$i=0;
break;
}
}
}
}
echo '<pre>'; print_r($ar);
return $pair.'--'.count($ar);
}
$a = [10, 20, 20, 10, 10, 30, 50, 10, 20, 80, 40];
$n = 11;
$b = sockMerchant($n, $a);
var_dump($b);
// Output:
/*
Array
(
[5] => 30
[6] => 50
[8] => 20
[9] => 80
[10] => 40
)
string(4) "3--5"
*/
?>
Demo

Find combination of array keys with values

In order to optimize the output I recently ran into a situation where I have to get the all the combinations of array keys inside an array. I looked into several places (including StackOverflow) but could not find the solution since most are related to permutation rather than combination.
Given this input
$input = ['jack' => 11, 'moe' => 12, 'shane' => 12];
Output should be something like this (the order inside an array does not matter).
$output = [
['jack' => 11],
['jack' => 11, 'moe' => 12]
['jack' => 11, 'moe' => 12, 'shane' => 12]
['moe' => 12],
['moe' => 12, 'shane' => 12]
['shane' => 12],
['shane' => 12, 'jack' => 11]
];
I tried this but after third iteration it does not work.
function combination(array $inputs, array $temp, &$collect) {
if (!empty($temp)) {
$collect[] = $temp;
}
for ($i = 0; $i < sizeof($inputs); $i++) {
$inputCopy = $inputs;
$elem = array_splice($inputCopy, $i, 1);
if (count($inputCopy) > 0) {
$temp[array_keys($elem)[0]] = array_values($elem)[0];
combination($inputCopy, $temp, $collect);
} else {
$temp[array_keys($elem)[0]] = array_values($elem)[0];
$collect[] = $temp;
$temp = [];
}
$i++;
}
}
Though I need this in PHP even Python (without using itertools combination), Java, Javascript will work for me.
I have found a way of doing what you want, but definitely, this is not a "fancy" solution. I would suggest you to work a little bit with it to find something better, but at least this gives you the result.
Here you go :
<?php
$baseArray = [
"joe" => 11,
"molly" => 12,
"sam" => 13,
];
function getAllPermutations($array = []) {
if (empty($array)) {
return [];
}
$result = [];
foreach ($array as $key => $value) {
unset($array[$key]);
$subPermutations = getAllPermutations($array);
$result[] = [$key => $value];
foreach ($subPermutations as $sub) {
$result[] = array_merge([$key => $value] , $sub);
}
}
return $result;
}
print_r(getAllPermutations($baseArray));
Output being :
Array
(
[0] => Array
(
[joe] => 11
)
[1] => Array
(
[joe] => 11
[molly] => 12
)
[2] => Array
(
[joe] => 11
[molly] => 12
[sam] => 13
)
[3] => Array
(
[joe] => 11
[sam] => 13
)
[4] => Array
(
[molly] => 12
)
[5] => Array
(
[molly] => 12
[sam] => 13
)
[6] => Array
(
[sam] => 13
)
) }
Hope this helped.
You read about really clever non-recursive algorithm here: PHP: Find every combination of an Array. You can adopt it (mostly copy and paste) to write generator function:
function keyCombinations($array)
{
$keys = array_keys($array);
$num = count($keys);
$total = pow(2, $num);
for ($i = 1; $i < $total; $i++) {
$combination = [];
for ($j = 0; $j < $num; $j++) {
if (pow(2, $j) & $i) {
$key = $keys[$j];
$combination[$key] = $array[$key];
}
}
yield $combination;
}
}
One important point here. In the original article $i initialized with 0, we initialize it with 1 to exclude empty array from the result.
Having this function you can get all combinations:
foreach (keyCombinations($input) as $combination) {
print_r($combination);
}
Here is working demo.
If, in your final combination, you include the empty set, your problem is equivalent to enumerating a binary number of "n" bits. Where "n" is the number of elements in your set.
You need a recursive algorithm like this one:
def comb(initialSet, results=[], currentIndex=0, currentResult=[]):
if currentIndex >= len(initialSet):
results.append( currentResult[:] )
else:
currentResult.append( initialSet[currentIndex] )
comb(initialSet, results, currentIndex + 1, currentResult)
currentResult.pop()
comb(initialSet, results, currentIndex + 1, currentResult)
return results

Getting specidic values from PHP arrays

Is there a way to get the first value from array, then the first value key + 3 ; then +6 then + 9 ans so on
Take this array for example,
array(1,2,5,14,19,2,11,3,141,199,52,24,16)
i want extract a value every 3 so the result would be
array(1,14,11,199,16)
Can i do that with existing PHP array function?
Use a for loop and increment the counter variable by 3.
for ($i = 0; $i <= count(your array); $i+3) {
echo $myarray[i]
}
The following is function that will handle extracting the values from a given array. You can specify the number of steps between each value and if the results should use the same keys as the original. This should work with regular and associative arrays.
<?php
function extractValues($array, $stepBy, $preserveKeys = false)
{
$results = array();
$index = 0;
foreach ($array as $key => $value) {
if ($index++ % $stepBy === 0) {
$results[$key] = $value;
}
}
return $preserveKeys ? $results : array_values($results);
}
$array = array(1, 2, 5, 14, 19, 2, 11, 3, 141, 199, 52, 24, 16);
$assocArray = array('a' => 1, 'b' => 2, 'c' => 5, 'd' => 14, 'e' => 19, 'f' => 2, 11, 3, 141, 199, 52, 24, 16);
print_r(extractValues($array, 3));
print_r(extractValues($array, 3, true));
print_r(extractValues($assocArray, 5));
print_r(extractValues($assocArray, 5, true));
?>
Output
Array
(
[0] => 1
[1] => 14
[2] => 11
[3] => 199
[4] => 16
)
Array
(
[0] => 1
[3] => 14
[6] => 11
[9] => 199
[12] => 16
)
Array
(
[0] => 1
[1] => 2
[2] => 52
)
Array
(
[a] => 1
[f] => 2
[4] => 52
)
Use a loop and check the key.
$result = array();
foreach($array as $key => $value) {
if ($key % 3 === 0) {
$result[] = $value;
}
}
Try below one:
<?php
$your_array = array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$every_3 = array();
$i = 0;
foreach($your_value as $value) {
$i++;
if($i%3==0){
$every_3[]=$value;
}
}
var_dump($every_3);
?>
Do like this
$arr=array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$narr=array();
for($i=0;$i<count($arr);$i=$i+3){
$narr[]=$arr[$i]
}
print_r($narr);
<?php
$mynums = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
foreach ($mynums as $key => $value) {
if ( $key % 3 === 0)
{
$newnum[] = $value;
}
}
var_dump($newnum);
?>
$data = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
$matches = array();
foreach($data as $key => $value)
{
if($key%3 === 0)
{
$matches[] = $value;
}
}
var_dump($matches);
The only way you could do it would be to use a loop, count the length of an array, and loop through using a % mathmatical operator.
It gives you a remainder of a division: http://au2.php.net/operators.arithmetic

Permutation of Array PHP

I have the following problem:
$multidmimensional = array(
[0] => array(
[0] => 1,
[1] => 2,
[2] => 3
);
[1] => array(
[0] => 5,
[1] => 6,
[2] => 7
);
...
[2] => array(
[0] =>,4
[1] => 5,
);
);
I can have one or more (nested) arrays, and lets take as an example the first two of the above arrays:
I should permutate them in the following way:
15
16
17
25
26
27
36
37
38
If I had for example those three arrays, I should get a result like this:
154
164
174
155
165
175
254
264
274
255
265
275
364
374
384
365
375
385
I am having some problems to make an algorithm that would fix this problem. Can anyone help me?
Thanks in advance.
That's a nice brain teasing question. Here's what I came up with, see the running demo for testing and adjusting.
$multidimensional = array(
0 => array(
0 => 1,
1 => 2,
2 => 3,
),
1 => array(
0 => 5,
1 => 6,
2 => 7,
),
2 => array(
0 => 4,
1 => 5,
),
); // just your input
$permutations = array();
$count = count($multidimensional);
for ($i = 0; $i < $count; $i++) {
$temp = array_map("permute",array($permutations),array($multidimensional[$i]));
$permutations = $temp[0];
}
print_r($permutations); // OUTPUT
function permute($base,$add) {
$result = array();
if (count($base) > 0) {
foreach ($base AS $val1) {
if (count($add) > 0) {
foreach ($add AS $val2) {
$result[] = $val1.$val2;
}
}
else {
$result = $base;
}
}
}
else {
$result = $add;
}
return $result;
}
I can not test it right now but this should work: (may contain typos)
function permute($arrays){
if(count($arrays)<2) return $arrays[0];//TODO error on count == 0
$array1 = array_shift($arrays);
$array2 = array_shift($arrays);
$results = array();
foreach($array1 as $elementOfOne){
foreach($array2 as $elementOfTwo){
$results[] = $elemnetOfOne . $elementOfTwo;
}
}
array_unshift($arrays, $results);
return permute($arrays);
}
$data = array
(
'1' => array(5, 6, 7),
'2' => array(9, 25, 14)
);
for($i=0; $i<=count(array_keys($data)); $i++) {
for($j=1; $j<=2; $j++) {
$values[$i][] = $data[$j][$i];
}
}
for($i=0; $i<count($values); $i++) {
shuffle($values[$i]);
}
$newData = array();
for($i=0; $i<3; $i++) {
for($j=1; $j<=2; $j++) {
$newData[$j][] = array_pop($values[$i]);
}
}
print_r($newData);
Fiddle

Categories