Argument Handling

suggest change

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) "-"
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Command Line Interface CLI:
* Argument Handling

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
49 Command Line Interface CLI
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR