Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpacking an array of arguments in php

Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:

args = [3, 6] range(*args)            # call with arguments unpacked from a list 

This is equivalent to:

range(3, 6) 

Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?

like image 867
sgibbons Avatar asked Nov 16 '08 20:11

sgibbons


People also ask

What is unpack PHP?

The unpack() function unpacks data from a binary string.

How can I return multiple values from a function in PHP?

PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.

How will you passing an argument to a function in PHP?

PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


2 Answers

In php5.6 Argument unpacking via ... (splat operator) has been added. Using it, you can get rid of call_user_func_array() for this simpler alternative. For example having a function:

function add($a, $b){   return $a + $b; } 

With your array $list = [4, 6]; (after php5.5 you can declare arrays in this way).

You can call your function with ...:

echo add(...$list); 
like image 190
Salvador Dali Avatar answered Sep 22 '22 07:09

Salvador Dali


You can use call_user_func_array() to achieve that:

call_user_func_array("range", $args); to use your example.

like image 24
Greg Avatar answered Sep 20 '22 07:09

Greg