views:

63

answers:

3

Hi everybody,

I was thinking about the possibility of accessing all the variables that are passed into an function, and merge them into an array. (Without passing variables into an array from the beginning)

Pseudo-code:

// Call function
newFunction('one', 'two', 'three' ) ;// All values are interpreted as a one rray in some way

// Function layout
newFunction( ) {    
   // $functionvariables =  array( All passed variables) 

    foreach ($functionvariable as $k => $v) {
        // Do stuff
    }
}
+10  A: 

http://php.net/func_get_args

Andy
Can't believe how easy that was. Thanks a lot for one of the fastest answers on SO I have gotten this far :)
Industrial
I was in a right place in a right time :D
Andy
+8  A: 

Take a look at func_get_args function. This is how you can build an array for them:

function test()
{
  $numargs = func_num_args();

  $arg_list = func_get_args();
  $args = array();

  for ($i = 0; $i < $numargs; $i++)
  {
    $args[] = $arg_list[$i];
  }

  print_r($args);
}
Sarfraz
+1  A: 

It can be useful to clearly identify that the items you are passing in should be treated as an array. For instance, set your function def to

function newFunction( $arrayOfArguments ) { 
    foreach($arrayOfArguments as $argKey => $argVal)
    { /* blah */ }
}
Zak