views:

38

answers:

4

Generally I pass an array of parameters to my functions.

function do_something($parameters) {}

To access those parameters I have to use: $parameters['param1']

What I would like to do, is run some sort of logic inside this function on those parameters that converts that array into normal variables. My main reasons is just that sometimes I have to pass a whole load of parameters and having to type $parameters['..'] is a pain.

foreach($parameters as $key=>$paremeter) {
    "$key" = $parameter;
}

I thought that might work.. but no cigar!

+1  A: 

Just extract the variables from array using extract:

Import variables into the current symbol table from an array

extract($parameters);

Now you can access the variables directly eg $var which are keys present in the array.

Sarfraz
+4  A: 

Use extract():

function do_something($parameters) {
    extract($parameters);

    // Do stuff; for example, echo one of the parameters
    if (isset($param1)) {
        echo "param1 = $param1";
    }
}

do_something(array('param1' => 'foo'));
BoltClock
And you can add "defaults" by doing something like `extract($parameters + array('param1' => null, 'param2' => null))`... One other thing though. If you're going to directly push `$parameters` to `extract`, I'd suggest adding an `array` type hint `function do_something(array $parameters)` to prevent trying to `extract` some other type...
ircmaxell
Use of extract() specially if it's outside a function or the parameters come from user input is a great security risk.
stillstanding
A: 

There is the extract function. This is what you want.

$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'
Rocket
+1  A: 

Try $$key=$parameter.

JacobM
That works too, but `extract($parameter)` probably is easier.
Rocket
I agree, but I figured the OP might want to know what was wrong with the specific approach he was using.
JacobM