Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php writing a function with unknown parameters?

Tags:

php

How would I go about writing a function in php with an unknown number of parameters, for example

function echoData (parameter1, parameter2,) {
    //do something
}

But when you call the function you can use:

echoData('hello', 'hello2', 'hello3', 'hello'4);

So that more parameters can be sent as the number of parameters will be unknown.

like image 567
Jai Avatar asked Aug 22 '11 11:08

Jai


2 Answers

func_get_args()

function echoData(){
    $args = func_get_args();
}

Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted

Similar functions about arguments

  • func_get_arg()
  • func_get_args()
  • func_num_args()
like image 199
genesis Avatar answered Sep 19 '22 15:09

genesis


Just for those who found this thread on Google.

In PHP 5.6 and above you can use ... to specify the unknown number of parameters:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4); // 10

$numbers is an array of arguments.

like image 44
Mac Avatar answered Sep 20 '22 15:09

Mac