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 Basic PHP Website (2018) Listing and Sorting Inventory Items Introducing Functions

I got stuck.

I don't know what to do. The error massage is "You need to pass the $numbers variable as an argument to array_sum()." I hope anyone help me.

index.php
<?php

$numbers = array(1,5,8);
/*
$sum = 0;
foreach($numbers as $number) {
    $sum = $sum + $number;
}

echo $sum;
*/
function array_sum(){
    $sum = 0;
    $sum = $numbers[0] + $numbers[1] + $numbers[2] ;

    return $sum;
}

array_sum();

?>

Steps

Remove foreach loop

$numbers = array(1,5,8);
$sum = 0;

    $sum = array_sum($number);


echo $sum;

2 Answers

Algirdas Lalys
Algirdas Lalys
9,389 Points

Hi ryota kurazono, The code below creates an array of numbers, loops through them one at a time, and sums their values. PHP actually has a native function that does this same thing: array_sum(). Some of PHP functions are internal like var_dump(), array_sum(), and there is plenty more. Array functions in PHP. So you just need to replace your foreach loop with this internal function.

$sum = array_sum($numbers);
Aananya Vyas
Aananya Vyas
20,157 Points

this worked for me:

$numbers = array(1,5,8);
$sum = 0;
 $sum = array_sum($numbers);
echo $sum;