Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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