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

The previous video does not sufficiently cover the topic to pose this question.

It would help to cover the topic more in depth before posing a confusing challenge.

palindromic_primes.php
<?php 


function mimic_array_sum($array){

  foreach($array as $element){


  }

}


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

?>
Hugo Paz
Hugo Paz
15,622 Points

Hi Remik,

Could you please explain what is confusing you in this challenge?

4 Answers

Hugo Paz
Hugo Paz
15,622 Points

I see you already created part of the function. Now you need to add: A variable that will contain the total, The logic to calculate the total, Return the total

function mimic_array_sum($array){

$total = 0;
  foreach($array as $element){
$total = $total + $element;

  }
return $total
}

I am lost with the question on creating a function that adds the total of each of the integers in the array and how to apply the function.

I do not understand how the $element is able to return total of the 3 integers. I understand the $total variable setting to 0, and calling it again but after that I am lost.

Hugo Paz
Hugo Paz
15,622 Points

The $element returns the value of each element inside of the array. We then add it to the current total.

Suppose we have an array with 3 values (23, 28, 35).

We pass this array to the mimic_array_sum function. The foreach loop runs through all the elements in the array, one at the time.

first iteration:

$total = 0, $element = 23, $total = 0 + 23

second iteration:

$total = 23, $element = 28, $total = 23 + 28

third and final iteration

$total = 51 $element = 35 $total = 51 + 35

the foreach loop finishes because you reached the end of the array, you now return the $total value which is 86.

ah now I get it -thanks