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

Vince Brown
Vince Brown
16,249 Points

mimic_array_sum() part 2 STUCK!!

<?php 

function mimic_array_sum($array){
  $sum = 0;
  foreach($numbers as $number) {
        $sum = $sum + $number;
    }
    return $sum;
  }


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

?>

I keep getting BUMMER! it doesnt look like mimic_array_sum is returning a value make sure you are using the return command

I am guessing it is something right under my nose but help would be appreciated.

3 Answers

Chase Lee
Chase Lee
29,275 Points

Vince Brown. This code should work. Sorry that I can't explain how it works I'm on a time crunch and got to get somewhere. Hopefully someone else can.

<?php

function mimic_array_sum($array) {
  foreach($array as $element) {
    $sum = array_sum($array);

  } return $sum;

} 

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

?>
Vince Brown
Vince Brown
16,249 Points

thank you Chase from what i can see the only difference between our code was I had $sum = 0 before i started the foreach loop, not 100% clear on why that would make a difference but thank you for the help !

Vince,

Take a look at your foreach statement. You are asking the foreach loop to loop through a variable called $numbers. However, you do not have the variable $numbers in your function. You should have used the name of the parameter $array. How you have it, the foreach loop loops through nothing and therefor is adding nothing and returning nothing To add, having the line $sum = 0 is fine as it is declaring and defining the variable that you are returning. You don't need to do that if you don't want to but it's okay if you do; it doesn't hurt the code.

Cheers!

Vince Brown
Vince Brown
16,249 Points

AH! lol I knew it was going to be something simple and under my nose. Thank you for pointing that out for me!