FlyingCat
FlyingCat

Reputation: 14280

How to assign arrays to functions arguments?

I am trying to assign values of my array to function's argument. I can't tell the length of the array but I want array value to be my functions argument. Ex:

$a= array {'1'=>'arg1', '2'=>'arg2', '3'=>'arg3'} ; //could have more than 3 values

function addArray('arg1','arg2','arg3'); //want to add values to argument.

Any thoughts? Thank a lot.

Upvotes: 0

Views: 130

Answers (2)

John Conde
John Conde

Reputation: 219894

You can use func_get_args() to get all of the arguments inside of the function.

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

Upvotes: 2

Ry-
Ry-

Reputation: 225144

You can call any function like that using call_user_func_array:

call_user_func_array('addArray', $a);

Upvotes: 2

Related Questions