PHP Function Reference

PHP func_get_arg() Function



The PHP func_get_arg() function returns the argument at the specified position from a user-defined function's argument list.

This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Syntax

func_get_arg(position)

Parameters

position Required. Specify the argument offset. Function arguments are counted starting from zero.

Return Value

Returns the specified argument, or false on error.

Exceptions

Generates a warning if called from outside of a user-defined function, or if position is greater than the number of arguments actually passed.

Example: func_get_arg() example

The example below shows the usage of func_get_arg() function.

<?php
function myFunction() {
  //getting the number of arguments passed
  $numargs = func_num_args();
  echo "Number of arguments: $numargs\n";

  //displaying the second argument
  if ($numargs >= 2) {
    echo "Second argument is: ".func_get_arg(1)."\n";
  }
}

myFunction(10, 20, 30);
?>

The output of the above code will be:

Number of arguments: 3
Second argument is: 20

Example: func_get_arg() example of byref and byval arguments

Consider the example below which demonstrates the effect of passing arguments by value and by reference while using this function.

<?php
function byVal($arg) {
  echo 'As passed    : '.func_get_arg(0)."\n";
  $arg = 'World';
  echo 'After change : '.func_get_arg(0)."\n";
}

function byRef(&$arg) {
  echo 'As passed    : '.func_get_arg(0)."\n";
  $arg = 'World';
  echo 'After change : '.func_get_arg(0)."\n";
}

$x = 'Hello';
byVal($x);
byRef($x);
?>

The output of the above code will be:

As passed    : Hello
After change : World
As passed    : Hello
After change : World

❮ PHP Function Handling Reference