0

I want to do this:

list($a, $b, $c) = array('a', 'b', 'c');
my_function($a, $b, $c);

BUT with unknown number of values in the array

my_function(some_function($array));

Any ideas?

xavip
  • 545
  • 5
  • 14
  • I think Machavity is right, but you can also look at http://php.net/manual/en/function.extract.php – mopo922 Dec 04 '14 at 19:01
  • duplicated call_user_func_array is the correct answer and aso the question is better explained than mine! – xavip Dec 04 '14 at 21:54

3 Answers3

1

You can pass the array to your function instead, this way you get all variables. If your array has keys, you can use the PHP extract() function.

// Build data array. Include keys as these will become the variable name later.
$data = array('a' => 'a', 'b' => 'b', 'c' => 'c');

// Call your function with data
my_function($data);

// Your function to parse data...
function my_function($data = NULL)
{
    // Verify you got data..
    if(is_null($data)){ return FALSE; }

    // Extract the array so that each value in the array gets assigned to a variable by it's key.
    extract($data);

    // Now you may echo values
    echo $a.$b.$c;
}

Another, more common option would be to loop through the array. Using a foreach loop you can reference each value of the array one at a time. This can be done like so:

// Build data array. Include keys as these will become the variable name later.
$data = array('a','b','c');

// Call your function with data
my_function($data);

// Your function to parse data...
function my_function($data = NULL)
{
    // Verify you got data..
    if(is_null($data)){ return FALSE; }

    // Loop through data to operate
    foreach($data as $item)
    {
        // Now you may echo values
        echo $item;
    }
}
Mikel Bitson
  • 3,583
  • 1
  • 18
  • 23
0

If you pass an array as a parameter to a function, you may use a foreach loop to iterate through an array of any length.

someFunction($returnedArray){

 foreach($returnedArray as $value){
  echo $value
 }
}

The foreach will go element by element, assigning the current index's value to (in this case) $value.

Anthony
  • 107
  • 5
-3

Just don't use list() function.

Pass an array to function. my_function(array(a, b, c,...)). It will be better if you will use hash array. Also extract() is not a good idea.

See: this blog and SO Post

Community
  • 1
  • 1
Sannek8552
  • 123
  • 1
  • 3
  • 2
    I downvoted this so I feel obligated to say why. Just saying that extract() is not a good idea gives users that search and find this thread no explanation behind why they should not use it. Instead, consider explaining the risks of extract() and/or not providing the same answer as others. – Mikel Bitson Dec 04 '14 at 21:07
  • 1. http://php.dzone.com/news/php-bad-practice-use-extract 2. http://stackoverflow.com/a/829454/1909755 Is it ok? – Sannek8552 Dec 05 '14 at 09:06