PHP Tutorial PHP Advanced PHP References

PHP $argv Variable



The PHP $argv variable contains an array of all the arguments passed to the script when running from the command line.

Note: The first argument $argv[0] is always the name that was used to run the script.

Note: This variable is not available when register_argc_argv in php.ini is disabled.

Example: $argv example

The example below demonstrates the usage of $argv variable.

<?php
var_dump($argv);
?>

When executing the above example with: php script.php arg1 arg2 arg3 arg4

The output of the above script will be similar to:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
  [4]=>
  string(4) "arg4"  
}

Example: adding multiple arguments

Consider one more example where this variable is used to add multiple number of arguments.

<?php
$n = $argc;
$result = 0;

for($i = 1; $i < $n; $i++)
  $result = $result + $argv[$i];

echo "Addition = ". $result;
?>

When executing the above example with: php script.php 10 20 30

The output of the above script will be similar to:

Addition = 60

Note: This variable is also available as $_SERVER['argv'].

❮ PHP - Predefined Variables