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?

2
  • I think Machavity is right, but you can also look at php.net/manual/en/function.extract.php Commented Dec 4, 2014 at 19:01
  • duplicated call_user_func_array is the correct answer and aso the question is better explained than mine! Commented Dec 4, 2014 at 21:54

3 Answers 3

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

Comments

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.

Comments

-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

2 Comments

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.