PHP subtract array values
You could avoid the foreach using array functions if you were so inclined.
The closure provided to array_map
docs below will subtract each $arr1
value from each corresponding $arr2
. Unfortunately array_map
won't preserve your keys when using more than one input array, so we use array_combine
docs to merge the subtracted results back into an array with the original keys:
$arr1 = array('a' => 1, 'b' => 3, 'c' => 10);
$arr2 = array('a' => 2, 'b' => 1, 'c' => 5);
$subtracted = array_map(function ($x, $y) { return $y-$x; } , $arr1, $arr2);
$result = array_combine(array_keys($arr1), $subtracted);
var_dump($result);
UPDATE
I was interested in how the array functions approach compared to a simple foreach, so I benchmarked both using Xdebug. Here's the test code:
$arr1 = array('a' => 1, 'b' => 3, 'c' => 10);
$arr2 = array('a' => 2, 'b' => 1, 'c' => 5);
function arrayFunc($arr1, $arr2) {
$subtracted = array_map(function ($x, $y) { return $y-$x; } , $arr1, $arr2);
$result = array_combine(array_keys($arr1), $subtracted);
}
function foreachFunc($arr1, $arr2) {
$ret = array();
foreach ($arr1 as $key => $value) {
$ret[$key] = $arr2[$key] - $arr1[$key];
}
}
for ($i=0;$i<10000;$i++) { arrayFunc($arr1, $arr2); }
for ($i=0;$i<10000;$i++) { foreachFunc($arr1, $arr2); }
As it turns out, using the foreach
loop is an order of magnitude faster than accomplishing the same task using array functions. As you can see from the below KCachegrind callee image, the array function method required nearly 80% of the processing time in the above code, while the foreach function required less than 5%.
The lesson here: sometimes the more semantic array functions (surprisingly?) can be inferior performance-wise to a good old fashioned loop in PHP. Of course, you should always choose the option that is more readable/semantic; micro-optimizations like this aren't justified if they make the code more difficult to understand six months down the road.
Php array subtract values
First you have to sort array, just to make sure that highest number is last one in array (otherwise it wont work, results wont be correct). Set starting value of result as last (highest) number of array, then loop through all numbers an subtract all numbers from highest one.
$arr = array(50,6,8,9);
$arr_len = count($arr)-1;
sort($arr);
$result = $arr[$arr_len];
for ($i = $arr_len-1; $i >= 0; $i--) {
$result -= $arr[$i];
}
echo $result;
If you want to subtract all values (no matter which one is highest) then use following code:
$arr = array(50,6,8,9);
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++) {
$result -= $arr[$i];
}
echo $result;
How to subtract number from array values using php?
Iterate array items and in loop check if target value is great that loop item, subtract item value from target value. If loop item is great than target value, subtract target value from loop item.
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item){
if ($subtract >= $item){
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
See result in demo
How to subtract value of array but still in position
For clarity and brevity, I'll refer to your input data as:
$array = [0, 3, 10, 5, 6, 9, 2, 7, 1, 4, 8, 11];
$deletes = [3, 5];
There is no sorting or preparation required for either of my snippets.
Output for both of the following are:
array (
0 => 0,
1 => 8,
2 => 4,
3 => 7,
4 => 2,
5 => 5,
6 => 1,
7 => 3,
8 => 6,
9 => 9,
)
Mostly function based approach: (Demo)
foreach (array_diff($array, $deletes) as $value) {
$result[] = array_reduce(
$deletes,
function ($carry, $item) use ($value) {
return $carry - ($value > $item);
},
$value
);
}
var_export($result);
*note: ($value > $item)
will evaluated as true
or false
, when used in arithmetic, true
= 1
and false
= 0
.
Language construct based approach: (Demo)
foreach ($array as $value) {
foreach ($deletes as $delete) {
if ($value == $delete) {
continue 2; // goto next value in outer loop without pushing
}
if ($value > $delete) {
--$value; // decrement value
}
}
$result[] = $value; // push adjusted value into result array
}
var_export($result);
The advantage in this snippet is that there are zero function calls and minimal variables declared.
Subtracting one array from another
Try this :
$array1 = array(251, 251, 130);
$array2 = array( 13, 13, 50);
$res = array();
for($i=0;$i<count($array1);$i++){
$res[$i] = $array1[$i]-$array2[$i];
}
echo "<pre>";
print_r($res);
PHP array values subtraction until the last value
I will go with recursion
<?php
$arr = [20,22,29,40,67,35,98,200,205,220];
function subArrayValues($array)
{
static $round = 0; //just to not output first array
if (count($array) < 2){
echo $array[0];
return;
}
$prevVal = null;
$newArray = [];
foreach ($array as $val){
if ($prevVal !== null){
$result = $val - $prevVal;
$newArray[] = $result;
}
$prevVal = $val;
}
if ($round > 0) echo implode(",", $array) . "\n";
$round++;
subArrayValues($newArray);
}
subArrayValues($arr);
This outputs
2,7,11,27,-32,63,102,5,15
5,4,16,-59,95,39,-97,10
-1,12,-75,154,-56,-136,107
13,-87,229,-210,-80,243
-100,316,-439,130,323
416,-755,569,193
-1171,1324,-376
2495,-1700
-4195
Live demo https://3v4l.org/JO3RX
Related Topics
Converting Human-Friendly Date to Milliseconds
Get All Work Days in a Week for a Given Date
Alternative to MySQLi_Fetch_All Needed
Fatal Error: Class 'Xsltprocessor' Not Found
Converting Dates with PHP for Datetime in SQL
How to Use Multiple PHP Header Content Types on the Same Page? Is This Possible
Wrapping a Div Around Every Third Item in a Foreach Loop PHP
Extracting Matches from PHP Regex
Sharing PHP Session ($_Session) Across Multiple Domain
PHP - How to Translate a Website into Multiple Languages
How to Launch a PHP Script at Apache Startup
Elegant Way to Search an PHP Array Using a User-Defined Function
How to Remove a Password from a PDF File Using PHP
PHP Making a Download Counter Without Leaving the Current Page
Is Auto-Initialization of Multi-Dimensional Hash Array Possible in Ruby, as It Is in PHP