Skip to content

Instantly share code, notes, and snippets.

@Dilden
Created May 11, 2015 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dilden/de602366cabefbfa88d2 to your computer and use it in GitHub Desktop.
Save Dilden/de602366cabefbfa88d2 to your computer and use it in GitHub Desktop.
Three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion using PHP
<?php
function one($a) {
$count = count($a);
$total = 0;
for ($i=0; $i < $count; $i++) {
$total = $total + $a[$i];
}
echo $total;
}
function two($b) {
$count = count($b);
$start = 0;
$total = 0;
while ($start < $count) {
$total = $total + $b[$start];
$start++;
}
echo $total;
}
function three($c) {
if(count($c) == 1) {
return $c[0];
}
else {
return array_shift($c) + three($c);
}
}
// $list = 174
$list = array(5, 10, 1, 89, 4, 65 );
one($list);
echo "<br>";
two($list);
echo "<br>";
echo three($list);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment