Search code examples
phpphp-8

PHP destructure into named function parameters


I want to destructure an array of values into function named parameters and not care about the array value order.

example:

$functionParams = [$name, $lastname, $age, $randomparam];

function x($age, $name, $randomparam, $lastname){

}

x(...functionParams);

this wont work, because it doesnt have the same order,

I would like my destructuration to fit something like named parameters, as

 x(...functionParams) -> x(name: $name, lastname: $lastname, age: $age, randomparam: $randomparam)

is there any way to achieve this ? Sorry if my explanation isnt propper


Solution

  • Thanks to Martin's answer I have been capable of achieving it.

    1. Instead of a normal array we could use an associative array.
    2. compact()

    instead of

    $functionParams = [$name, $lastname, $age, $randomparam];
    

    we do

    $functionParamsCompact = compact('name', 'lastname', 'age', 'randomparam');
    

    then we can just x(...functionParamsCompact)

    Compact function docs