How to Use the func_get_arg() Function in PHP

In PHP, for getting a mentioned value from the argument passed as a parameter, you can use the inbuilt func_get_arg() function.

The syntax of this function is demonstrated below:

mixed func_get_arg( int $arg )

This function can accept only one parameter that is $arg.

The func_get_arg function returns the mentioned argument on success and FALSE, otherwise.

To be clear, we will demonstrate an example:

<?php

// Function definition 
function w3docs($a, $b, $c)
{
  
  // Call the func_get_arg() function 
  echo "Print second argument: " . func_get_arg(1) . "\n";
}

// Function call 
w3docs('hello', 'php', 'w3docs');

?>

As an output, the following will turn out:

  Print second argument: php

Errors

Sometimes, while using the func_get_arg() function, errors can occur.

Below, we will consider the two main situations that can cause errors.

  • Once the argument offset value is higher than the actual value of the arguments passed as the function parameter.
  • Once the function is not called inside the user-defined function.

Here is an example:

<?php

// Function definition 
function w3docs($a, $b, $c)
{
  
  // Printing the sixth argument 
  // that doesn't exist 
  echo "Printing the sixth argument: " . func_get_arg(5) . "\n";
}

// Function call 
w3docs('hello', 'php', 'w3docs');

?>

The output will look as follows:

  Warning:  func_get_arg():  Argument 5 not passed to function in 
    [...][...] on line 4

Describing the func_get_arg() Function

This PHP function is capable of getting a particular argument from the arguments list of a user-defined function.

You can use it along with func_get_args() and func_num_args() for allowing a user-defined function to accept a variable-length argument list.

Do you find this helpful?

Related articles