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

I don't know where i am doing it wrong. Please help 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.

palindromic_primes.php
<?php 

$sum=0;
function mimic_array_sum($array){
  foreach($array as $element){
   $sum = $sum ;
  }
  return $sum ;


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

?>

1 Answer

The task is asking you to create a function that takes an array as a parameter, calculates the sum of all the elements within that array, and returns the result. Here is the code:

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

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

  function mimic_array_sum($array){
    $a=0;
    foreach($array as $element){
      $a += $element;
    }
    return $a;
  }
?>

First we create the variable $palindromic_primes and assign to it an array with the elements 11, 757 and 16361. Then, we call the function mimic_array_sum($palindromic_primes), store the result in $sum and then echo it.

The function micmic_array_sum works as follows:

  • it accepts one parameter called $array.
  • it starts by initializing a variable $a with the value 0.
  • for each element in the array, do:
    • increment the variable $a with that element
    • repeat the above until all the elements have been used.
  • return the result $a.

Hope this helps.

That was great, thanx for the explanation i do understand the question now.