Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a PHP associative array as function call arguments? [duplicate]

Assume that there is a function with some parameters and I have an associative array (or a simple object with public properties - which is almost the same, since I can always use a type cast (object)$array) whose keys correspond to the function parameter names and whose values correspond to function call arguments. How do I call it and pass them in there?

<?php
function f($b, $a) { echo "$a$b"; }
// notice that the order of args may differ.
$args = ['a' => 1, 'b' => 2];
call_user_func_array('f', $args); // expected output: 12 ; actual output: 21
f($args); // expected output: 12 ; actual output: ↓
// Fatal error: Uncaught ArgumentCountError:
// Too few arguments to function f(), 1 passed
like image 839
whyer Avatar asked Oct 21 '25 14:10

whyer


1 Answers

It turns out, I just had to use variadic function named param unpacking feature introduced in PHP 8 ( https://wiki.php.net/rfc/named_params#variadic_functions_and_argument_unpacking ) :

f(...$args); // output: 12

Prior to PHP 8, this code produces the error: Cannot unpack array with string keys.

Secondly, it turns out that call_user_func_array also works as expected in PHP 8 (see https://wiki.php.net/rfc/named_params#call_user_func_and_friends for explanation):

call_user_func_array('f', $args); // output: 12

- while it still outputs incorrect '21' in older versions.

like image 120
whyer Avatar answered Oct 23 '25 03:10

whyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!