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

Adam Duffield
Adam Duffield
30,494 Points

PHP Functions 2/3 Sum of all numbers in an array using foreach

The task wants me to return the sum of all the numbers in the array below.

I think I'm having some issues with the foreach loop and the $element variable.

Here is my code

<?php

function mimic_array_sum($array){ foreach($array as $element){ $total = $array as $element; } return $total;

}

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

echo mimic_array_sum($palindromic_primes);

?>

1 Answer

Jack Choi
Jack Choi
11,420 Points

I think the issue is with the line here

$total = $array as element;

This would probably give an error. I think this might be what you're looking for:

$total = $total + $element;

or

$total += $element;
Adam Duffield
Adam Duffield
30,494 Points

Cheers Jack! Rookie mistake! Spent far too much time on this one that i forgot the basics :)