PHP Command Line Interface (CLI) Argument Handling


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.


printf("You called the program %s with %d arguments\n", $argv[0], $argc - 1);
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
array(6) {
  string(13) "argc.argv.php"
  string(19) "--this-is-an-option"
  string(20) "three words together"
  string(2) "or"
  string(12) "in one quote"
  string(34) "but multiple spaces counted as one"

If the PHP script is run using -r:

$ php -r 'var_dump($argv);'
array(1) {
  string(1) "-"

Or code piped into STDIN of php:

$ echo '<?php var_dump($argv);' | php
array(1) {
  string(1) "-"