4

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.

1
  • 1
    Why does it need to be "destructured"? Why can't you do doStuff( myArray['page'], myArray['subpage'] )? Commented Aug 14, 2018 at 18:48

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

1 Comment

New? The splat operator came in 5.6, which was 3-4 years ago.
0

You just call the function with the array parts:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.