创建一个使用php中的函数传递的值数组[关闭]

I am trying to get the sum of all the numbers passed to the function but am having some issues.

I want to show the result 17 when array sum is echoed, array('1','4','9','3');

result_time(1);
result_time(4);
result_time(9);
result_time(3);

$items = array(); 

function result_time($Num){

    $items[] = $Num;        
}

echo array_sum($items);

Can anyone explain what im doing wrong here?

That's not the best way, but you can try adding global $items; to your result_time function.

function result_time($Num)
{
    global $items;
    $items[] = $Num;        
}

You can read more infos about variable scope here : http://php.net/manual/en/language.variables.scope.php

$items inside the function and $items outside the function are in two different scopes, they're completely different variables. The $items inside the function is reset to empty on every call and does also not affect the $items outside the function. In essence, your function does nothing. Really properly you should use a class do this:

class Result {

    protected $items = array();

    public function add($num) {
        $this->items[] = $num;
    }

    public function getResult() {
        return array_sum($this->items);
    }

}

$r = new Result;
$r->add(1);
...
echo $r->getResult();

You may also make the value inside the function accumulate using a static variable:

function result_time($Num){
    static $items = array();
    $items[] = $Num;
    return $items;
}

result_time(1);
...
$result = result_time(3);

echo array_sum($result);

That's not really a good idea though. You may also share the scope of the variables using the global keyword, but this is a bad idea and I'm not going to advertise it. Learn about variable scope and structure your code properly.

It looks like you already know all the values you'll want to sum as your code progresses. Why not add them to an array directly?

<?php    
$result_times = array();
array_push($result_times, 1);
// some code
array_push($result_times, 4);
// other code
array_push($result_times, 9);

echo array_sum($result_times);