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?
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?
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;
}
}
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.
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.