How to implement a function that can take arbitrary parameters in PHP?

Does PHP have such a function?

+3
source share
4 answers

You can use the following functions:

Example:   

function my_sum() { // <--- No parameters! :D
    $total = func_num_args();
    $numbers = func_get_args();

    if ($total < 1) {
        trigger_error('Less than one number :(');
        return 0;
    } else {
        // Calculate the sum
        $sum = array_sum($numbers);
        return ($sum / $total);
    }
}

// Usage:
echo my_sum(1, 2, 5, 109, 10231);
?>
+5
source

Use the function func_get_args(). It will give you an array of all the parameters passed to this function.

0
source

, , , , func_get_args(), .

0

, - , . :

function my_sum($data){
    $sum = 0;
    foreach($sum as $value){
        $sum+=$value;
    }
    return $sum;
}

echo my_sum(array(1, 2, 5, 109, 10231));

. , . :

$data = array(
    'date' => '10/4/06',
    'name' => 'biggles',
    'occupation' => 'pilot'
);
add_person($data);

. , . , , , .

0

Source: https://habr.com/ru/post/1730309/


All Articles