Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Simple PHP Application Working With Functions Introducing User-Defined Functions

Code Challenge Task # 3

Hi can someone help me solve task #3 for this challenge and explain the concept? I am confusing here.

palindromic_primes.php
<?php 
function mimic_array_sum ($array) {
  $sum = 0;
  foreach($array as $arr => $element) {
    $sum+=$element;
  }
 return $sum; 
}  

$sum = mimic_array_sum ($array); 
echo $sum;


$palindromic_primes = array(11, 757, 16361);

?>

1 Answer

Grace Kelly
Grace Kelly
33,990 Points

Hi Jason,

The task asks for you to create a function that can add a number of values, you've got the right idea with your code, except you don't need the => element as you're not dealing with associative arrays in this case!! If you remove that from your foreach loop and instead add the $arr value to your $sum variable it should work fine!! Here's an example of how the function could look:

<?php 

function mimic_array_sum($array) {
  $total = 0;
  foreach($array as $arr) { //loop through each element in the array
  $total+= $arr; // add the element to $total
  }
  return $total;
}
?>

now, looking to apply it to the $palindromic_primes array, you need to pass the array through the mimic_array_sum function in order for it to work, like so:

<?php
$palindromic_primes = array(11, 757, 16361);

$sum = mimic_array_sum($palindromic_primes); //pass the $palindromic_primes array through the function

echo $sum;
?>

Hope this helps!!