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

Anthony Randazzo
Anthony Randazzo
13,072 Points

Function not summing to the right number

Function not summing to the right number... help?

<?php

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

$sum = 0; function mimic_array_sum($palindromic_primes) { foreach($palindromic_primes as $palindromic_prime) { $sum = $sum + $palindromic_prime; return $sum; }

}

?>

4 Answers

Jeremy Germenis
Jeremy Germenis
29,854 Points

Your foreach loop is overwriting the return $sum value each time it runs. The return should be the last thing your function does.

Andrew Shook
Andrew Shook
31,709 Points

The problem is your return statement. You have it in the foreach loop so the loop only adds the first number before it is terminated by the return statement.

Patrick Koch
Patrick Koch
40,496 Points

Hello Anthony

In your example you where just a little bit too fast with your return value; If you want to have the total sum of your array you need to let the server finishing adding all number before you call a return. For me it helps sometimes to see every single step what the loop is doing, in the code below I let server echo out sum every time after adding another element of the array. After the loop I want to return $sum.

 <?php

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

function mimic_array_sum($palindromic_primes) { 
    $sum = 0; 

    foreach($palindromic_primes as $palindromic_prime){ 
        $sum = $sum + $palindromic_prime; 
        echo $sum . "<br>";
    }
    return $sum;
}

echo "Here is the final value of sum " . mimic_array_sum($palindromic_primes);

?>

I hope I could help you!

Bella Ratmelia
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bella Ratmelia
Front End Web Development Techdegree Graduate 28,947 Points

the challenge specifies : First, create a function named mimic_array_sum. It should receive one argument, an array of numbers to be summed. Name that argument $array. (Be sure to specify a pair of curly brackets where the code this function executes will go.)

I saw that you give the argument name of $palindromic_primes instead. Try to change them to $array and see if it works :)