0

I have a PHP function that is expecting an unknown number of arrays as parameters.

function cartesianProduct() { ... }

It is expecting me to do something like this:

cartesianProduct(
  array('blue', 'green', 'red'),
  array('apples', 'oranges', 'bananas')  
);

But I'm constructing the arrays beforehand and am having trouble passing them in.
For example:

$arrs = array(
  array('blue', 'green', 'red'),
  array('apples', 'oranges', 'bananas')
);
cartesianProduct($arrs);

Passing in the arrays this way doesn't work - obviously it is seeing it as one single array parameter.

How can I 'expand' my $arrs parameter or call the function in a different way to make the function think I'm passing the inner arrays?

Thanks

Jason Varga
  • 1,949
  • 2
  • 21
  • 29

1 Answers1

2

You can use call_user_func_array to accomplish that.

$arrs = array(
    array('blue', 'green', 'red'),
    array('apples', 'oranges', 'bananas')
);

call_user_func_array('cartesianProduct', $arrs);

The first argument is the function name you want to call and the second is an indexed array of parameters that will be passed to it.

Guilherme Sehn
  • 6,727
  • 18
  • 35