Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAnthony Randazzo
13,072 PointsFunction not summing to the right number
Function not summing to the right number... help?
<?php
$palindromic_primes = array(11, 757, 16361);
$sum = 0; function mimic_array_sum($palindromic_primes) { foreach($palindromic_primes as $palindromic_prime) { $sum = $sum + $palindromic_prime; return $sum; }
}
?>
4 Answers
Jeremy Germenis
29,854 PointsYour foreach loop is overwriting the return $sum value each time it runs. The return should be the last thing your function does.
Andrew Shook
31,709 PointsThe problem is your return statement. You have it in the foreach loop so the loop only adds the first number before it is terminated by the return statement.
Patrick Koch
40,496 PointsHello Anthony
In your example you where just a little bit too fast with your return value; If you want to have the total sum of your array you need to let the server finishing adding all number before you call a return. For me it helps sometimes to see every single step what the loop is doing, in the code below I let server echo out sum every time after adding another element of the array. After the loop I want to return $sum.
<?php
$palindromic_primes = array(11, 757, 16361);
function mimic_array_sum($palindromic_primes) {
$sum = 0;
foreach($palindromic_primes as $palindromic_prime){
$sum = $sum + $palindromic_prime;
echo $sum . "<br>";
}
return $sum;
}
echo "Here is the final value of sum " . mimic_array_sum($palindromic_primes);
?>
I hope I could help you!
Bella Ratmelia
Front End Web Development Techdegree Graduate 28,947 Pointsthe challenge specifies : First, create a function named mimic_array_sum. It should receive one argument, an array of numbers to be summed. Name that argument $array. (Be sure to specify a pair of curly brackets where the code this function executes will go.)
I saw that you give the argument name of $palindromic_primes instead. Try to change them to $array and see if it works :)