I have following array:
array(50,6,8,9)
I wanna subtract all values on array
Result must be: (50-6-8-9=equals):
27
Something like array_sum
but unlike !
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;
There you go: a simple loop that iterates over the array and subtracts the values
$arr = [50, 6, 8, 9];
function array_subtract(array $arr){
$subtraction = $arr[0];
for ($i = 1; $i < count($arr); $i++) {
$subtraction -= $arr[$i];
}
return $subtraction;
}
$val = array_subtract($arr);
I know the OP already has a solution, but I'd like to add a function which uses a foreach
-loop instead of a for
-loop, in case the array has some funky keys (which will create a false result and generate PHP Notices).
function array_subtract(array $input) {
$result = reset($input); // First element of the array
foreach (array_slice($input, 1) as $value) { // Use array_slice to avoid subtracting the first element twice
$result -= $value; // Subtract the value
}
return $result; // Return the result
}
This does the same thing as the functions in the other answers, but is more reliable because it doesn't care what the keys in the array is.
$array = ["one" => 50, "two" => 6, 8, 9];
echo array_subtract($array); // Outputs 27
If you had used the sample-array above with a for
-loop, you'd get "Undefined offset X in.." notices, and it would return a wrong result.
It can also be simplified to using native array_*
functions. array_shift()
gets the first element of the array, and removes it from the array. array_sum()
sums the remainder of the array. Subtract those two, and you get the same result.
function array_subtract(array $input) {
return array_shift($input) - array_sum($input);
}