Arguments are passed to the program in a manner similar to most C-style languages. $argc
is an integer containing the number of arguments including the program name, and $argv
is an array containing arguments to the program. The first element of $argv
is the name of the program.
#!/usr/bin/php
printf("You called the program %s with %d arguments\n", $argv[0], $argc - 1);
unset($argv[0]);
foreach ($argv as $i => $arg) {
printf("Argument %d is %s\n", $i, $arg);
}
Calling the above application with php example.php foo bar
(where example.php contains the above code) will result in the following output:
You called the program example.php with 2 arguments
Argument 1 is foo
Argument 2 is bar
Note that $argc
and $argv
are global variables, not superglobal variables. They must be imported into the local scope using the global
keyword if they are needed in a function.
This example shows the how arguments are grouped when escapes such as ""
or \
are used.
Example script
var_dump($argc, $argv);
Command line
$ php argc.argv.php --this-is-an-option three\ words\ together or "in one quote" but\ multiple\ spaces\ counted\ as\ one
int(6)
array(6) {
[0]=>
string(13) "argc.argv.php"
[1]=>
string(19) "--this-is-an-option"
[2]=>
string(20) "three words together"
[3]=>
string(2) "or"
[4]=>
string(12) "in one quote"
[5]=>
string(34) "but multiple spaces counted as one"
}
If the PHP script is run using -r
:
$ php -r 'var_dump($argv);'
array(1) {
[0]=>
string(1) "-"
}
Or code piped into STDIN of php
:
$ echo '<?php var_dump($argv);' | php
array(1) {
[0]=>
string(1) "-"
}