If you can change your inputs to an (associative) array, you can make use of array_sum
and a function from "Finding the subsets of an array in PHP" (more specific: Walf's answer) to automatically determine the possible combinations:
function power_set($array) {
$results = [[]];
foreach ($array as $key => $value) {
foreach ($results as $combination) {
$results[] = $combination + [$key => $value];
}
}
// Remove the first empty set
array_shift($results);
// Sort descending by amount of elements
$order = array_map('count', $results);
uksort($results, function($key_a, $key_b) use ($order) {
$comp = $order[$key_b] - $order[$key_a];
if ($comp == 0) {
$comp = $key_a - $key_b;
}
return $comp;
});
return array_values($results);
}
function zero_sums($inputs) {
$subsets = power_set($inputs);
foreach ($subsets as $subset) {
if (array_sum($subset) == 0) {
echo implode(" & ", array_keys($subset)).PHP_EOL;
}
}
}
Sample outputs:
zero_sums(["a" => 1, "b" => -1, "c" => 2]);
// Prints "a & b"
zero_sums(["a" => -0.5, "b" => -0.5, "c" => 1]);
// Prints "a & b & c"
zero_sums(["a" => 1, "b" => -1, "c" => 2, "d" => -1]);
// Prints "b & c & d" / "a & b" / "a & d"
zero_sums(["a" => -1, "b" => -1, "c" => 2, "d" => 1, "e" => -1]);
// Prints "a & b & c & d & e" / "a & b & c" / "a & c & e" / "b & c & e" / "a & d" / "b & d" / "d & e"