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

Tast 3/3: How to return the value from this function?

Task 3 asks me to store the return value of the function in a variable called $sum and echo it out. I do this, but I can't make it work. I tried many different approaches...

palindromic_primes.php
<?php 


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


echo $sum = mimic_array_sum($palindromic_primes);
$palindromic_primes = array(11, 757, 16361);

?>

For instance, in a different attempt, I called the function without giving it a parameter ($palindromic_primes).

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Stefan,

You're close.

First, you need to move (cut and paste) the $palindromic_primes array to above the function. If you try to call the function before the variables are declared, it will error out.

Second, you have to store the result into the variable first, before you echo it out. So just delete echo from your statement and have $sum = mimic_array_sum($palindromic_primes);

Then, on another line (below the now stored variable), you just echo out the variable echo $sum;

Hope that helps. Keep Coding! :)

Thanks, Jason, that did it.