How to pass variable number of arguments to a PHP function

Sep 20th, 2007
You may need to pass variable number of arguments due to many reasons. Many times you have list with you, which include values passed from users and then number of elements in a list are not fixed.

I will discuss two methods of passing variable number of arguments to PHP function, and both are very simple.

1. Passing arguments using PHP array

<?php

function funct1($arr1) {
    // Now you have your familiar array with you.
    // Use it using foreach, for, etc.
    // if you have passed associate array then you can check for array's key also
    …
    …

   return true;

}

// Create array

$temp = array('arg1', 'arg2', 'arg3');

$output = funct1($temp);
?>

2. Another method is little unfamiliar but more efficient method for passing variable number of argument to a function

<?php

function funct1 () {
    …

    $ct = func_num_args(); // number of argument passed

    for ($i=0; $i<$ct; $i++) {

        echo func_get_arg($i); // get each argument passed
    }

    return true;

}

$output = funct1('argument1', 'argument2', 'argument3');

?>

Now, you can pass variable number of arguments depending upon requirements. Using array method, meaning keys can be used to recognize the usage of arguments passed.

Related article: Value Exchange from Javascript/HTML page to PHP and from PHP page to JavaScript

 
Possibly Related posts:
Comments are closed. You are welcome to write on Facebook page.