PHP可以轻松地将数组结构化为单个变量以传递给函数

Say I have a PHP array like this.

array(2) { ["page"]=> string(1) "a" ["subpage"]=> string(4) "gaga" }

I want to pass the contents of this array to a function call, of a function like this:

function doStuff($page, $subpage) {
 // Do stuff
}

How could I destructure this array into individual objects to pass to the function? The variables of the function will always be in the same order that the corresponding keys are in the array.

You can use array_values to get the values out of the array and then call_user_func_array to call your function using an array of values as an argument.

<?php
$input = array( 'page' => 'a', 'subpage' => 'gaga' );
$values = array_values($input);
$result = call_user_func_array('doStuff', $values);

Or, in newer versions of PHP (>=5.6.x), you can use argument unpacking with the ... operator:

<?php
$input = array( 'page' => 'a', 'subpage' => 'gaga' );
$values = array_values($input);
$result = doStuff(...$values);

You just call the function with the array parts:

doStuff($array['page'], $array['subpage']);

If you are sure about the order of the keys you can use the newer ... operator:

doStuff(...array_values($array));