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

Willie Allison
Willie Allison
2,035 Points

How do you write the code for the mimic_array_sum to work right?

I have been trying to get this to work but the preview to see what your code is doing has not worked for me in the last few lessons so I can't tell if the code works without submitting it. I don't get it. I understand the course is suppose to get harder but didn't expect that.

palindromic_primes.php
<?php 
function mimic_array_sum($array) {
  $total = array_sum();
  foreach($array as $element) {
  }
  return $total
}
$palindromic_primes = mimic_array_sum(11, 757, 16361);

?>

1 Answer

Hello Willie,

By the look of this code I can tell that you are probably talking about task 2 from this challenge. You need a variable to store the total sum. Before the foreach this variable should be 0 because we haven't started to add to it the numbers from the array. Every time we go through and element in the foreach we should add it to this total variable. After the loop finishes we should return the total.

The code will look something like this:

<?php 
function mimic_array_sum($array) {
  $total = 0;
  foreach ($array as $element) {
    $total += $element;
  }

  return $total;
}

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

?>

I used a shorthand here : $total += $element;

this is the same as $total = $total + $element;