1

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

3
  • The array $functionParams doesn't know the variable name of the data given to it; in the same way a person in a restaurant doesn't know the name of the dish the chef presents to them, they only can see the ingredients, not what the ingredients combined together are called. So your array doesn't know the $age item, it knows the age value but not that this is the age. Solution: Use a named array key and pass that to the function to process. Commented Nov 8, 2022 at 9:21
  • does this question help you? Commented Nov 8, 2022 at 9:23
  • Yes ! thanks, Martin. i will post the answer and credit you Commented Nov 8, 2022 at 9:58

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.