PHP func_get_args Function

func_get_args() Function

With PHP, you can pass parameters into a function or you can get them inside a function using the func_get_args() function. Let me take you through the example. There are two functions.

One function will pass in the parameters and create an indexed array with those variables. After that, the $variables array is returned and shown with the print_r() function.

Since the $output variable was made equal to the function, the returned array takes on the name of the variable. Thus, that is why print_r($output) is used to print the array rather than print_r($variables).

The second function will pass in parameters, but, the function will not pass them along since there are none show between the get_parameters(). Remember, the first function passed them inside the function with pass_parameters($a,$b,$c). Hopefully, this difference is very clear for you.

Even though they are not passed into the second function, they can be accessed using the built in PHP function called func_get_args(). With func_get_args(), you will have an array of the parameters.

From calling the function with get_parameters('one','two','three'), the array will be those three strings. Thus, the array $variables in the second function contains those three values.

Like the first function, the array is returned and takes on the name $output. Just like the first example, your array will yield the same results with the print_r() function.

Example

<?php 

function pass_parameters($a,$b,$c) {

$variables = array($a,$b,$c);

return $variables;

}

function get_parameters() {

$variables = func_get_args();

return $variables;

}


$output = pass_parameters('one','two','three');

print_r($output);

echo "<br/>";


$output = get_parameters('one','two','three');

print_r($output);


Browser Output

When you load this page in your browser, you will see the results of each identical array. Now, you have two methods in your toolkit for accessing parameters passed into a function.

Array ( [0] => one [1] => two [2] => three )
Array ( [0] => one [1] => two [2] => three )