Unlimited number of function parameters in PHP

Posted on December 6th, 2011 by Wayne May in PHP | 0 comments

Every so often I find myself needing to pass an unknown amount of arguments into a function. For example, assume you want to create a function to add a bunch of variables: add( $a, $b, $c, $d, … ) This can easily be done using the PHP function func_get_args().

1
2
3
4
5
6
7
8
9
10
11
    function add()
    {  
        $total  = 0;
        $args = func_get_args();  
 
        foreach ($args as $key => $val)
        {  
            $total += $val;  
        }  
        return $total;
    }

You can then call the function with as many arguments as you want.

1
    echo add( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );

Post a comment

Hello guest, care to post a comment?