tags:

views:

148

answers:

4

I have two indexed arrays $measurements[] and $diffs[] ,

$measurements[] is filled with values from a database and the $diffs[] gets values from a function which calculates the difference from two measurements.

When I have a collection of different measurements in $measurements[] I want to add a value to just one array element in the $diffs[] array and then loop through it, then where the array element got updated check for corresponding index array element in the $measurements[] array en deduct it from there.

What I'm trying to accomplish is to have a specific difference deducted from a corresponding measurement when I have a collection of measurments.

Is this possible in php and how would I go about doing this.

Edit: to make it more descriptive (english is not my first language nor is php)

$measurements Array ( [0] => 1469 [1] => 1465 [2] => 739 [3] => 849 ) 

$diffs Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 )

I would like to update $diffs array index [2] => 200 so it becomes

Array ( [0] => 0 [1] => 0 [2] => 200 [3] => 0 )

and then subtract $diffs array index [2] from $measurements array index [2] in this case 739 - 200

I sincerely hope this makes it more clear.

+4  A: 

I'm sure it's possible... it sounds like you need just a few foreaches and some basic arithmetic.

But more specific than that, I can't help you. I can't understand your description of the problem.


Edit: Now, with more information on the table, the code isn't all that complex. Here's how I would do it:

foreach ($measurements as $index => $measurement) {
  $measurements[$index] -= $diffs[$index]; // subtract the negative difference from the measurement.
  unset($diffs[$index]);           // clear the modifier after use.
}

This code iterates through each element in the $measurements array, and subtracts a number from the corresponding index in $diffs. This code doesn't require that $diffs has matching size with $measurements, because PHP will coerce a missing index-value to zero.

Henrik Paul
A: 

Maybe something like this if your array is 100. Syntax might be off and like previous poster not sure if I understood your problem.

for ( $counter = 0; $counter <= 100; $counter += 1) {
    $measurements[$counter] = $measurements[$counter] - $diff[$counter];
}
AaronLS
$counter <= 100 ?!
Ilya Biryukov
Is that a question?
AaronLS
A: 

If I understand you correctly, you want to first change something in the $diffs array, and then subtract ONLY the updated element in that array from the element in the $measurements array where the indexes correspond.

I guess you'll have to make a copy of the $diffs first, then make a change to it, then compare it to the original one (like through use of foreach()) and update the values if something has changed at a particular index.

'Scuse me if I misunderstood!

JorenB
A: 

To answer you questions: "yes" and "effort"

George Jempty