Sorry for the confusing title…
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn’t seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I “print_r” the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I’m populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname"is a string, not an array.call_user_func_arraywill pass each element in$arr_resultsas argument toarray_intersect.array_intersectexpects arrays as arguments, but each item in$arr_resultsis a string, not an array.All you have to do is create an array of arrays instead of array names:
Right, you create a variable, lets say
arr_0which will point to array. But there is still a difference between the variable namearr_0and the string containing the variable name"arr_0". You create an array of strings, and that just won’t work. PHP does not know that the string contains a name of a variable. For example, consider this:Based on your logic, it should output the first element of the array, but it does not, because
$arris a string, not an array, although it contains the name of a variable.You’d have to use
eval, but you really should not. You could also use variable variables again:that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.