note 76501 deleted from function.array-sum by levim
| From: | levim@php.net | Date: | Tue, 18 Mar 2014 19:43:49 +0000 |
| Subject: | note 76501 deleted from function.array-sum by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198969@lists.php.net to get a copy of this message | ||
Note Submitter: didikdwi at gmail dot com
----
This is a simple approach to subtract array, both indexed and associative.
function array_sub($arr) {
if (!is_array($arr) || count($arr) == 0) {
return false;
} else {
// get first element
$base = array_shift($arr);
if (count($arr) == 1) {
// If only one element, return its
return $base;
}
foreach ($arr as $val) {
$base -= $val;
}
return $base;
}
}
// example
$arr1 = array(3, 2, 3);
echo array_sub($arr1); // Output: -2
$arr2 = array(3.5, 2, 3);
echo array_sub($arr2); // Output: -1.5
$arr3 = array('a' => 3, 'b' => 2, 'c' => 3);
echo array_sub($arr3); // Output: -2