Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP easily destructure array into individual variables to pass to function

Tags:

arrays

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.

like image 632
Rando Hinn Avatar asked Sep 06 '25 13:09

Rando Hinn


1 Answers

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);
like image 125
Zach Bloomquist Avatar answered Sep 08 '25 11:09

Zach Bloomquist