Can a PHP function accept an unlimited number of parameters?

13,665

Solution 1

In PHP, use the function func_get_args to get all passed arguments.

<?php
function myfunc(){
    $args = func_get_args();
    foreach ($args as $arg)
      echo $arg."/n";
}

myfunc('hello', 'world', '.');
?>

An alternative is to pass an array of variables to your function, so you don't have to work with things like $arg[2]; and instead can use $args['myvar']; or rewmember what order things are passed in. It is also infinitely expandable which means you can add new variables later without having to change what you've already coded.

<?php
function myfunc($args){
    while(list($var, $value)=each($args))
      echo $var.' '.$value."/n";
}

myfunc(array('first'=>'hello', 'second'=>'world', '.'));
?>

Solution 2

You can use these functions from within your function scope:

  • func_get_arg()
  • func_get_args()
  • func_num_args()

Some examples:

foreach (func_get_args() as $arg)
{
    // ...
}

for ($i = 0, $total = func_num_args(); $i < $total; $i++)
{
    $arg = func_get_arg($i);
}

Solution 3

if you have PHP 5.6+ , then you can use

function sum(...$numbers) 

functions.variable-arg-list

Solution 4

You will have 3 functions at your disposal to work with this. Have the function declaration like:

function foo()
{
    /* Code here */
}

Functions you can use are as follows

func_num_args() Which returns the amount of arguments that have been passed to the array

func_get_arg($index) Which returns the value of the argument at the specified index

func_get_args() Which returns an array of arguments provided.

Solution 5

You can use func_get_args() inside your function to parse any number of passed parameters.

Share:
13,665
Starx
Author by

Starx

Website | Careers | GitHub | Freelancer | Odesk | Facebook | Google+ | Twitter | YouTube | Blog Stackoverflow* Top member from Nepal: 2011 &amp; as of March 2012 1st User from Nepal to reach 15K+, 20K+, 25K+, 30K+ on Stackoverflow to get Silver Badge in php (182th world wide), jquery (134th world wide) Projects: jQuery Fancy Menu [git] jQuery Tiny Highlighter [git] Stackexchange

Updated on June 03, 2022

Comments

  • Starx
    Starx about 2 years

    In PHP there are functions like unset() that support any number of parameter we throw at them.

    I want to create a similar function that is capable of accepting any number of parameters and process them all.

    Any idea, how to do this?