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 trialShaun Kelly
35,560 PointsBuilding a simple PHP application
Stuck on this and its really bugging me.
Write the code inside this mimic_array_sum() function. That code should add up all individual numbers in the array and return the sum. You’ll need to use a foreach command to loop through the argument array, a working variable to keep the running total, and a return command to send the sum back to the main code.
<?php
function mimic_array_sum($array) {
}
$palindromic_primes = array(11, 757, 16361);
?>
1 Answer
Grace Kelly
33,990 PointsHi Shaun, we use the foreach method to loop through the array so we can access its values and add them, we also need to create a $sum variable inside the function so we can add the values in the array together, lastly we must return the $sum variable. Putting all this information together, we can do something like this:
<?php
function mimic_array_sum($array) {
$sum = 0; //create the $sum variable
foreach($array as $number) { //go through each value in the array (labelled $number)
$sum = $sum + $number; //add the $number value to the $sum variable
}
return $sum //return the value of $sum
}
$palindromic_primes = array(11, 757, 16361);
?>
Hope that helps!!