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

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;