Skip to content

Instantly share code, notes, and snippets.

@seeruk
Last active August 29, 2015 14:07
Show Gist options
  • Save seeruk/ce1b5a6950d4b5681acf to your computer and use it in GitHub Desktop.
Save seeruk/ce1b5a6950d4b5681acf to your computer and use it in GitHub Desktop.
<?php
/**
* Sum Interface
*
* @author Elliot Wright <elliot@byng.co>
*/
interface SumInterface
{
/**
* Sum a list of numbers
*
* @param array $numbers
* @param number $total
*
* @return number
*/
public static function sum(array $numbers, $total = 0);
}
/**
* Recursive Summing Class
*
* @author Elliot Wright <elliot@byng.co>
*/
class RecursiveSum implements SumInterface
{
/**
* {@inheritDoc}
*/
public static function sum(array $numbers, $total = 0)
{
$total += array_pop($numbers);
if (count($numbers) > 0) {
return self::sum($numbers, $total);
} else {
return $total;
}
}
}
$numbers = [10, 20, 30, 40, 50];
$sum = RecursiveSum::sum($numbers);
var_dump($sum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment