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 trial

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!!