Jump to content

[SOLVED] Use array values as function parameters


blogical

Recommended Posts

I have an array. I would like to use the values of the array as the parameter list when calling a function. Here is an example, where what I seek is $mystery_function_x:

 

$parameters = array('1234.45', 1);
$function = 'number_format';

// I want the same result as: 
//number_format('1234.45', 1);
  $function( $mystery_function_x($parameters) );

 

This needs to work for calling different functions, accepting different numbers of parameters, so I cannot reference the parameters directly with subscript notation. I'm looking for something like 'array_values', only returning a list (like 'values' in perl.) Or perhaps I'm thinking about this in the wrong way, but I feel like I'm overlooking the obvious.

 

Any insight appreciated. Thanks!

:)

 

<?php
$parameters = array('1234.45', 1);
$function = 'number_format';

if (count($parameters) == 1) 
{
    $function($parameters[0]);
} 
else if (count($parameters) == 2) 
{
    $function($parameters[0], $parameters[1]);
}
else if (count($parameters) == 3) 
{
    $function($parameters[0], $parameters[1], $parameters[2]);
}
?>

 

I think I have seen this method used in a few frameworks, so there is a good chance it is the only way to do it.

@premisio: unfortunately that hits the same problem.

 

@flyhoney: that's close to what I ended up having to do, using subscript notation to access the values directly, although I built the code string and eval'd it so as not to limit it to a particular number of parameters. I avoid eval if possible, but at least I'm not interpolating anything into the eval'd code.

 


$parameters = array('1234.45', 1);
$function = 'number_format';
$functioncall = 'return( $function( ';
$paramprep = array();
for ($x=0 ; $x < count($parameters); $x++ ) $paramprep[] = '$parameters['.$x.']';
$functioncall .= implode(', ', $paramprep) . ' ) );';
eval($functioncall);

 

Thanks for taking a look.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.