Reputation: 1334
I have a custom function array_sequence_merge()
. With the help of func_get_args()
, any number of arguments can be passed to the function as long as they are all ARRAYS.
The problem is, the arrays that need to be passed into function are created dynamically with WHILE loop of unknown size:
while($n < count($site)) {
$siten = $site[$n];
$sql = "SELECT url FROM `".$$siten->domain."`";
$result = $con->query($sql);
while($row = $result->fetch_array()){
${$siten."_url_list"} = $row['url'];
}
}
So. for example, if there 3 elements in $site
array, the resulting 3 arrays will be:
$element1_url_list
$element2_url_list
$element3_url_list
Now they have to be passed to array_sequence_merge()
function to get:
array_sequence_merge($element1_url_list, $element2_url_list, $element3_url_list);
Each time the amount of elements in $site
array is different, and so is the amount of dynamically created XXXXX_url_list
arrays.
Question: How do I pass those array variables into the function?
The way I approached it, was to store dynamically created array variable name in a temporary array right after it is created in a WHILE loop. But I am not sure what to with it next... If only I could do some kind of "argument list concatenation", something like:
$arguments = $temporary_array[0];
while($n < count($temporary_array)) {
$arguments .= ",".$temporary_array[$n];
}
array_sequence_merge($arguments);
Just not sure how to do it right...
Upvotes: 0
Views: 994
Reputation: 2069
Use call_user_func_array like this:
call_user_func_array('array_sequence_merge', $arguments);
with $arguments being your array of parameters.
Then every element of the array is handled as a separate parameter of "array_sequence_merge".
Edit To achieve something like
array_sequence_merge($element1_url_list, $element2_url_list, $element3_url_list, ...);
you have to change the code like this:
$arguments = [];
while($n < count($site)) {
$siten = $site[$n];
$sql = "SELECT url FROM `".$$siten->domain."`";
$result = $con->query($sql);
while($row = $result->fetch_array()){
$arguments[] = $row['url'];
}
}
// $result contains the return value of the array_sequence_merge function call
$result = call_user_func_array('array_sequence_merge', $arguments);
So basically instead of creating $elementN_url_list variables write them into the array $arguments and pass it to call_user_func_array as second parameter.
Upvotes: 2