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

daniwao
daniwao
13,125 Points

Function Error

The error I'm getting is that my function is not "summing" up the array but I feel that my function is doing that. Here's the code below.

<?php function mimic_array_sum($array) { $count = 0; foreach ($array as $arrays) { $count = $count + $arrays; return $count; } };

$palindromic_primes = array(11, 757, 16361); echo $count = mimic_array_sum($palindromic_primes); ?>

2 Answers

David Kaneshiro Jr.
David Kaneshiro Jr.
29,247 Points

Hi dan iwao

It looks like you put the return $count; inside the foreach loop. Move it outside of the loop and that should fix your problem. Your current code is returning the value and exiting the function before it can move to the second item in the array.

Keith Kelly
Keith Kelly
21,326 Points

Didn't mean to repeat your answer. You must have posted while I was typing mine up.

David Kaneshiro Jr.
David Kaneshiro Jr.
29,247 Points

Hehe, it happens. I usually write up my answer, highlight it, copy it, then refresh the page to see if someone posted the same answer that I was writing up. If all is clear, I paste it back in the answer box then click the post answer button. I'm a bit obsessively compulsive about it.

Keith Kelly
Keith Kelly
21,326 Points

You are pretty close, but your return value should be outside the foreach loop like so:

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

  foreach ( $array as $element ) {
    $sum = $sum + $element;
  }

  return $sum;

}

That way you have completely summed all of the values in the array prior to returning the final sum. You only want to return the sum once when all of the array elements have been looped through.