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 trialBenjamin White
5,388 PointsUser Defined Functions task 2 of 3, keep getting 16361!
I know this has been answered to death, believe me I've read through all of them.
This is my code, which produces only the final number in the array:
<?php
function mimic_array_sum($array) {
$sum = 0; foreach($array as $number); { $sum = $sum + $number; } return $sum; }
$palindromic_primes = array(11, 757, 16361); $sum = mimic_array_sum($palindromic_primes); echo $sum;
?>
Please tell me where I am wrong. Tradition would have me perform ritualistic suicide should I not pass. Not really, but thanks.
3 Answers
Nicholas Mejia
23,800 PointsYou've got a few syntax errors in there. You don't need that semi colon after the foreach arguments.
Here's the revised code
function mimic_array_sum($array){
$sum = 0;
foreach($array as $number){
$sum = $sum + $number;
}
return $sum;
}
$palindromic_primes = array(11, 757, 16361);
$sum = mimic_array_sum($palindromic_primes);
echo $sum;
?>
Benjamin White
5,388 PointsYou are both correct. I tried my best to review every single line for error before posting, but my brain has (on more than one occasion) overlooked a single digit. Thank you for the explanation. Had you just provided the code, I would not have known the difference.
Nicholas Mejia
23,800 PointsOne last thing to keep in mind is your formatting. If the code you posted above was your actual formatting, you should really start separating statements and writing your blocks like mine. You should always do whats most comfortable for you, but there are a lot of best practices you should follow that will help you track those silly semi colons. That being said, I still miss a closing bracket or quote every now and then...just don't tell anyone....
Benjamin White
5,388 PointsYeah, mine was actually formatted correctly, but cut-and-paste put it together funny. I'm new to this, so I didn't know how to post the code properly.
Colin McGraw
15,337 PointsI think it's that semi-colon right after you start the foreach, causing the loop to not actually happen. When I removed it and ran that code it echoed the sum correctly.