1

I'm trying to extract values from an array, and pass them to a function where they'll be used. I've used echo inside the function for this example.

I'm using extract to get all the values.

Thing is, this wont work. Do you see how this can be done?

<?php

$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more

$g = extract($my_array);

foo($g);

function foo($g) {
    echo 'My name is '.$a.', and I am '.$b;
}

?>
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 1
    Are you looking for [`call_user_func_array()`](http://php.net/call_user_func_array)? – kero May 17 '14 at 11:23
  • @kingkero Actually, I'm trying it with what you suggested. How is it done? I keep getting some error or the other in spite of following the examples correctly. – Norman May 17 '14 at 11:30

2 Answers2

1

Functions in PHP have a different scope, so the variables $a, $b etc. aren't available inside your function. Trying to use them inside the function would result in Undefined variable notices (if you enable error reporting, that is).

Right now, you're storing the return value of extract() (which is the total number of variables parsed) into your function. You want the values instead, so change your function like so:

function foo($array) {
    extract($array);
    echo 'My name is '.$a.', and I am '.$b;
}

Note that I've moved the extract() call inside the function. This way, you wouldn't pollute the global scope with random variables (which may have undesired results and will make your debugging hard for no reason).

Now you can call your function, like so:

foo($my_array);

Output:

My name is Prince, and I am Funky

Demo

It's better to avoid extract() altogether, though. See: What is so wrong with extract()?

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
-2

You can pass your array in your function as you do with any other variable

$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more

foo($my_array);

function foo($arrayData) 
{
    echo 'My name is '.$arrayData['a'].', and I am '.$arrayData['b'];
}
andrew
  • 2,058
  • 2
  • 25
  • 33