Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get all arguments as array?

Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I'm working with something like this:

function foo($a1 = null, $a2 = null, $a3 = null, $a4 = null){     if ($a1 !== null) doSomethingWith($a1, 1);     if ($a2 !== null) doSomethingWith($a2, 2);     if ($a3 !== null) doSomethingWith($a3, 3);     if ($a4 !== null) doSomethingWith($a4, 4); } 

But I was wondering if I can use a solution like this:

function foo(params $args){     for ($i = 0; $i < count($args); $i++)         doSomethingWith($args[$i], $i + 1); } 

But still invoke the function the same way, similar to the params keyword in C# or the arguments array in JavaScript.

like image 325
MiffTheFox Avatar asked May 06 '09 08:05

MiffTheFox


2 Answers

func_get_args returns an array with all arguments of the current function.

like image 186
bb. Avatar answered Sep 19 '22 02:09

bb.


If you use PHP 5.6+, you can now do this:

<?php function sum(...$numbers) {     $acc = 0;     foreach ($numbers as $n) {         $acc += $n;     }     return $acc; }  echo sum(1, 2, 3, 4); ?> 

source: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

like image 35
Joren Avatar answered Sep 23 '22 02:09

Joren