W3docs

How to Use the func_get_arg() Function in PHP

In this snippet, we will demonstrate to you how to use one of the common PHP functions: func_get_arg().

In PHP, to retrieve a specific argument passed to a function, you can use the built-in <kbd class="highlighted">func_get_arg()</kbd> function.

The syntax of this function is demonstrated below:

Syntax

mixed func_get_arg( int $arg )

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This function accepts a single parameter: <kbd class="highlighted">$arg</kbd>.

The <kbd class="highlighted">func_get_arg</kbd> function returns the specified argument on success, or FALSE otherwise.

To demonstrate, here is an example:

php use func_get_arg function

<?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');

?>

Print second argument: php

Errors

Sometimes, using the <kbd class="highlighted">func_get_arg()</kbd> function can trigger warnings.

Below are the two main situations that cause errors:

  • When the argument index exceeds the number of arguments passed to the function.
  • When the function is called outside of a user-defined function.

Here is an example:

php func_get_arg() function usage

<?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');

?>

php func_get_arg() function usage, output

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

To prevent this warning, you can safely check the number of arguments using func_num_args() before calling func_get_arg():

function w3docs($a, $b, $c)
{
  if (func_num_args() > 5) {
    echo "Printing the sixth argument: " . func_get_arg(5) . "\n";
  } else {
    echo "Argument 5 is not available.\n";
  }
}

Describing the func_get_arg() Function

This PHP function retrieves a specific argument from a user-defined function's argument list.

It is often used alongside <kbd class="highlighted">func_get_args()</kbd> and <kbd class="highlighted">func_num_args()</kbd> to handle variable-length argument lists.

Note: Because this function returns mixed, be mindful of type coercion when used in strict types mode.