How to convert array to multiple variables in PHP

2019-09-06 02:19发布

问题:

I have an array:

$r = array(1,2,42,55);

and I want to call encrypt(); function of hashids

which takes input like this:

encrpyt(1,2,42,55);

I tried extract($r) but it does not work.

回答1:

You can call a callback on each of the elements of the array. check array_map if it helps.



回答2:

It's ugly, but there's this:

eval("encrypt(" . implode(",", $r) . ");");

Here's your obligatory reminder that eval is potentially dangerous and to be used rarely if ever!

Edit: Forgot about call_user_func_array. That's your answer! Sample code:

$r = array(1,2,42,55);
$hashids = new Hashids\Hashids('this is my salt');
$hash = call_user_func_array(array($hashids, "encrypt"), $r);


标签: php arrays hash