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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With