0

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!

2
  • 2
    I can see why -> $paremeter :-) Commented Aug 25, 2010 at 19:52
  • 1
    Not to mention that you're assigning it to a literal string (which isn't possible)... $$key = would work, but not "$key" = ... Commented Aug 25, 2010 at 20:08

4 Answers 4

4

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'));
Sign up to request clarification or add additional context in comments.

2 Comments

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...
Use of extract() specially if it's outside a function or the parameters come from user input is a great security risk.
3

Try $$key=$parameter.

2 Comments

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

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.

Comments

0

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

$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.