Page 1 of 1

Send an array as a variable number of arguments

Posted: Fri Dec 28, 2007 12:20 am
by anjanesh

Code: Select all

<?php
foo("string-1");
foo(array("string-a", "string-b", "string-c"));

function foo($a, $p1 = "", $p2 = "") # This cannot be changed to variable number of params
 {
        //if (!is_array($a)) $a = array($a);
        foo1($a);
 }

function foo1() # variable number of params
 {
        $args_count = func_num_args();
        $args = func_get_args();

        foreach ($args as $arg)
         {
                echo $arg."\n";
         }
 }
?>
Any way to get this to output ?

Code: Select all

string-1
string-a
string-b
string-c
How do I send an array as a variable number of arguments to a function ?

Thanks

Posted: Fri Dec 28, 2007 12:26 am
by ianhull

Code: Select all


implode('', $a);


Posted: Fri Dec 28, 2007 1:56 am
by anjanesh
imlode will combine the array values into a string and send it as a single argument.
foo1(implode('', $a)); will end up as foo1("string-astring-bstring-c");
what I need is it to send it as foo1("string-a", "string-b", "string-c");

Posted: Fri Dec 28, 2007 5:54 am
by arjan.top
Try with call_user_func_array()

Re: Send an array as a variable number of arguments

Posted: Fri Dec 28, 2007 6:51 am
by webspider
anjanesh wrote:

Code: Select all

<?php

function foo($a, $p1 = "", $p2 = "") # This cannot be changed to variable number of params
 {
           foo1($a);
 }

function foo1() # variable number of params
 {
       
 }
?>
function foo1($a) is called with argument $a, but in function definition there is no argument. Is this possible in php?

Re: Send an array as a variable number of arguments

Posted: Fri Dec 28, 2007 7:59 am
by Zoxive
webspider wrote: function foo1($a) is called with argument $a, but in function definition there is no argument. Is this possible in php?

Code: Select all

$args_count = func_num_args();
$args = func_get_args();
Have a look at the manual for those (Rarely used) functions.

Posted: Fri Dec 28, 2007 9:20 am
by webspider
$args is becoming a two dimensional array. but we sent a one dimensional array $a.
then should we output like this :?

Code: Select all

foreach ($args as $arg)
        {
           foreach($arg as $val)
           {
                echo $val."\n";
           }
        }