Use array as argument list in PHP - php

Is there a PHP equivalent to the python func(*[array]) feature to use the array as a series of arguments for the function? I can't seem to find one online.
Example usage in Python:
def f(a,b):
print(a, b)
f('abc', 'def')
f(*['abc', 'def'])
Outputs
abc def
abc def
Thanks in advance for any help.
EDIT: This is different to this because that question wants to use an array as a parameter, whereas I want to use an array as a series of parameters.

"..." is Argument unpacking, and can be used in the function definition, or the call
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
Given a ...array() as the function argument, collect the (remaining) arguments from the call into an array variable:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);

In PHP < 5.6 that would be call_user_func_array('f', ['abc', 'def']);
In 5.6+, you can do f(...['abc', 'def']); instead.

Related

Php | How to pass unknown length array of arguments to function individually

I have an array of arguments that are in order for a function.
The number of items in the array differ. I want to be able to pass in each item in the array individually to the functions (eg...func(arg1, arg2, arg3, arg4);). Opposed to just passing in the whole array.
Keep in mind, I do not know the length of the array, it differes depending on which function I am calling.
since PHP 5.6 you have the Variable-length argument lists so you can call your function like this:
$arr = array(1, 2, 5, "ten");
and you can send all the elements in the $arr to a function by calling it like this:
myFunc(...$arr);
If you mean you have a function that its argument is an array, you can use foreach to fetch all the array elements:
function my_func($arg_array)
{
foreach($arg_array as $key=>$value)
{
......
}
....
}
But if you mean you have a function that has unknown number of arguments you can use func_get_args function that returns an array containing arguments as an array.
function my_func()
{
foreach(func_get_args() as $key=>$value)
{
......
}
....
}
Use : call_user_func_array("functionName", $arrayofArgs);
<?php
function unknown($arg1,$arg2,$arg3){
echo "arg1 = $arg1 <br>";
echo "arg1 = $arg2 <br>";
echo "arg1 = $arg3 <br>";
}
$array = [
"arg1" => "Hi",
"arg2" => "Marhaba",
"arg3" => "Hola",
"arg4" => "foo"
];
call_user_func_array("unknown", $array);
?>
and you can call the function from class by passing the first param as array of ["className","methodName"]
php Docs :
http://php.net/manual/en/function.call-user-func-array.php
In PHP you have:
func_num_args()
func_get_args()
func_get_arg()
for that purpose.
EDIT
If you are fine using PHP 5.6 then you have splat operator. Quoting sample from docs (link):
<?php
function add($a, $b, $c) {
return $a + $b + $c;
}
$operators = [2, 3];
echo add(1, ...$operators);

What is the meaning of three dots (...) in PHP?

While I am installing Magento 2 on my Server, I got an error. After investigating the code and found that there is are three dots (...), which is producing the error. I included the code I found below:
return new $type(...array_values($args));
What is this operator called, and what is its purpose?
This is literally called the ... operator in PHP, but is known as the splat operator from other languages. From a 2014 LornaJane blog post on the feature:
This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
(This would print I'D LIKE 6 APPLES)
The parameters list in the function declaration has the ... operator in it, and it basically means " ... and everything else should go into $strings". You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings array, ready to be used.
There are TWO uses for the ellipsis (...) PHP token—think of them as packing an array and unpacking an array. Both purposes apply to function arguments.
Pack
When defining a function, if you need a dynamic number of variables provided to the function (i.e., you don't know how many arguments will be provided to that function when called in your code), prefix the ellipsis (...) token to a variable name—e.g., ...$numbers—to capture all (remaining) arguments provided to that function into an array assigned to the named variable—in this case $numbers—that is accessible inside the function block. The number of arguments captured by prefixing ellipsis (...) can be zero or more.
For example:
// function definition
function sum (...$numbers) { // use ellipsis token when defining function
$acc = 0;
foreach ($numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2, 3, 4); // provide any number of arguments
> 10
// and again...
echo sum(1, 2, 3, 4, 5);
> 15
// and again...
echo sum();
> 0
When packing is used in function instantiation, prefixing ellipsis (...) to a variable name captures all remaining arguments, i.e., you can still have any number—zero or more—of initial, fixed (positional) arguments:
function sum ($first, $second, ...$remaining_numbers) {
$acc = $first + $second;
foreach ($remaining_numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2); // provide at least two arguments
> 3
// and again...
echo sum(1, 2, 3, 4); // first two are assigned to fixed arguments, the rest get "packed"
> 10
...the prefixed ellipsis variable captures all the rest. For this reason it must be the final function argument.
Unpack
Alternatively, when calling a function, if the arguments you provide to that function are previously combined into an array use a ellipsis (...) token prefixed variable "inline" to convert that array variable into individual arguments provided to the function. When any number of function arguments are replaced with an ellipsis prefixed variable, each array element is assigned to the respective function argument variable named in the function definition.
For example:
function add ($aa, $bb, $cc) {
return $aa + $bb + $cc;
}
$arr = [1, 2, 3];
echo add(...$arr); // use ellipsis token when calling function
> 6
$first = 1;
$arr = [2, 3];
echo add($first, ...$arr); // used with positional arguments
> 6
$first = 1;
$arr = [2, 3, 4, 5]; // array can be "oversized"
echo add($first, ...$arr); // remaining elements are ignored
> 6
Unpacking is particularly useful when using array functions to manipulate arrays or variables.
For example, unpacking the result of array_slice:
function echoTwo ($one, $two) {
echo "$one\n$two";
}
$steaks = array('ribeye', 'kc strip', 't-bone', 'sirloin', 'chuck');
// array_slice returns an array, but ellipsis unpacks it into function arguments
echoTwo(...array_slice($steaks, -2)); // return last two elements in array
> sirloin
> chuck
Every answer refers to the same blog post, besides them, here is the official documentation about variable-length argument lists:
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array
It seems "splat" operator is not an official name, still it's cute!
In PHP 7.4 the ellipsis is also the Spread operator:
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
Source: https://wiki.php.net/rfc/spread_operator_for_array
Meaning is that it decomposes an associative array to a list. So you do not need to type N parameters to call a method, just one. If method allows a decomposed parameter and if parameters are of the same type.
For me, the most important thing about splat operator is that it can help to typehint array parameters:
$items = [
new Item(),
new Item()
];
$collection = new ItemCollection();
$collection->add(...$items); // !
// what works as well:
// $collection->add(new Item());
// $collection->add(new Item(), new Item(), new Item()); // :(
class Item {};
class ItemCollection {
/**
* #var Item[]
*/
protected $items = [];
public function add(Item ...$items)
{
foreach ($items as &$item) {
$this->items[] = $item;
}
}
}
it saves some effort on type control, especially while working with huge collections or very object-oriented.
Important to notice is that ...$array do decompose an array despite the type of its items, so you can go the ugly way also:
function test(string $a, int $i) {
echo sprintf('%s way as well', $a);
if ($i === 1) {
echo('!');
}
}
$params = [
(string) 'Ugly',
(int) 1
];
test(...$params);
// Output:
// Ugly way as well!
But please don't.
PHP 8 update - named arguments
Since PHP 8 you can now decompose associative arrays, it is, arrays that have keys for them values. If you use it in function that has arguments named the same, PHP will transfer values to proper variables:
$arr = [
'pi' => 3.14,
'r' => 4,
];
function circ($r, $pi) {
return 2*$pi*$r;
}
// so that call
circ(...$arr);
// will be effectively a call of
circ(pi: 3.14, r: 4);
and you can slightly less bother about order of parameters.
PHP 8.1 update - new syntax for creating callable
Despite usage with arrays, ... earned a whole new, very useful functionality that help creating callable from any context:
$f = strtoupper(...); // creating a callable
echo $f('fo');
class test {
public function func($a) {
echo $a . PHP_EOL;
}
}
$f = (new test)
->func(...); // creating a callable
$f('x');
In PHP 8.1, this syntax "(...)" is used as a new way to create callables.
Before PHP 8.1:
$callable = [$this, 'myMethod'];
After PHP 8.1:
$callable = $this->myMethod(...);
Source: https://wiki.php.net/rfc/first_class_callable_syntax
To use this feature, just warn PHP that it needs to unpack the array into variables using the ... operator. See here for more details, a simple example could look like this:
$email[] = "Hi there";
$email[] = "Thanks for registering, hope you like it";
mail("someone#example.com", ...$email);
This is the so called "splat" operator. Basically that thing translates to "any number of arguments"; introduced with PHP 5.6
See here for further details.
It seems no one has mentioned it, so here to stay[It will also help Google (& Other SEs) guide devs who asking for Rest Parameters in PHP]:
As indicated here its called Rest Parameters on JS & I prefer this meaningful naming over that splat thing!
In PHP, The functionality provided by ...args is called Variadic functions which's introduced on PHP5.6. Same functionality was used to be implemented using func_get_args().
In order to use it properly, you should use rest parameters syntax, anywhere it helps reducing boilerplate code.

Lambda equivalent from Python in PHP

I am trying to replicate this code in PHP:
pool = ThreadPool(num_parts)
pool.map(
lambda f: migrate(client, user_id=user_id, files=f), all_files)
What is the equivalent structure to use in PHP to iterate over an array while calling a function?
Double bonus points for using it in context of multi-threading on PHP :)
In Python, lambda creates an anonymous function at run time.
Say:
def f(x):
return x * 2
Or:
f = lambda x: x * 2
Will both create a function f that returns x times 2, except lambda can create an anonymous function, that can be assigned to a variable or passed as argument without being given a name.
A similar effect can be accomplished in PHP like this:
$f = function ($x) { return $x * 2; }
Now the variable $f is holding a function and can be used as $f(value).
The same way as in Python, you can create this anonymous function directly as an argument without assigning it to a variable or giving it a name. Example:
$arr = [1, 2, 3, 4, 5];
$arr = array_map(function ($x) { return $x * 2; }, $arr);
// $arr is now [2, 4, 6, 8, 10]
Iterate over a array while calling a function,
$array = array(1,2,3);
$var = 'foo';
array_walk($array, function ($value, $key) use ($var) {
# do something
});

PHP sort 2d array by index (non-associative)

This code does not run properly, but it suggests what I am trying to do:
function sort_2d_by_index($a,$i) {
function cmp($x, $y) {
// Nested function, can't find $i
// (global $i defeats the purpose of passing an arg)
if ($x[$i] == $y[$i]) { return 0; }
return ($x[$i] < $y[$i]) ? -1 : 1;
}
usort($a,"cmp");
return $a;
}
There HAS to be a much better way to do this. I've been examining ksort(), multisort(), and all sorts of sorts until I'm sort of tired trying to sort it all out.
The situation is this: I've got a 2-d array...
array(
array(3,5,7),
array(2,6,8),
array(1,4,9)
);
...and I want to sort by a column index. Say, column [1], would give this result:
array(
array(1,4,9),
array(3,5,7),
array(2,6,8)
);
Does someone have a link (I'm sure this has been asked before), or could someone say "you need foosort, definitely". Thanks very much.
In the documentation of array_multisort it is mentioned that it can be used for this kind of thing.
You can't avoid creating an array that consists of only one column:
$sort_column = array();
foreach ($a as $row)
$sort_column []= $row[1]; // 1 = your example
array_multisort($sort_column, $a);
This sorts both arrays synchronously so that afterwards your whole array is sorted in the same order as the $sort_column array is.
As of PHP 5.3 you can use a closure (pass $i into the function) by defining your cmp function like this:
$cmp = function($x, $y) use ($i) { ... };
You can use use to access $i:
function cmp($x, $y) use ($i) {
// $i now available
if ($x[$i] == $y[$i]) { return 0; }
return ($x[$i] < $y[$i]) ? -1 : 1;
}
http://www.php.net/manual/en/function.sort.php#99419
phpdotnet at m4tt dot co dot uk
Simple function to sort an array by a specific key. Maintains index association.

How to implement a function that can take arbitary parameters in PHP?

Does PHP has such a feature?
You can use these functions:
func_get_arg » http://php.net/manual/en/function.func-get-arg.php
func_get_args » http://php.net/manual/en/function.func-get-args.php
fung_num_args » http://php.net/manual/en/function.func-num-args.php
Example:
function my_sum() { // <--- No parameters! :D
$total = func_num_args();
$numbers = func_get_args();
if ($total < 1) {
trigger_error('Less than one number :(');
return 0;
} else {
// Calculate the sum
$sum = array_sum($numbers);
return ($sum / $total);
}
}
// Usage:
echo my_sum(1, 2, 5, 109, 10231);
?>
Use the function func_get_args(). It will give you an array of all the parameters passed to that function.
Sure, make a function with no parameters, call it with whatever you want, and inside the function use func_get_args() to get the actual arguments.
Prehaps a better way is to pass one argument, that is actually an array of arguments.
eg:
function my_sum($data){
$sum = 0;
foreach($sum as $value){
$sum+=$value;
}
return $sum;
}
echo my_sum(array(1, 2, 5, 109, 10231));
I often use an associative array to pass arguments to a function. This is very usefull if the arguments being submitted are optional, or change in nature.
eg:
$data = array(
'date' => '10/4/06',
'name' => 'biggles',
'occupation' => 'pilot'
);
add_person($data);
This will also allow for better error detection. if you have many many arguments, it is quite possible to get them in the wrong order. plus if you extend or modify teh function it is more likely to keep working with existing code.

Categories