(PHP 4 >= 4.3.0, PHP 5, PHP 7)
getopt — Gets options from the command line argument list
$options
[, array $longopts
[, int &$optind
]] )Parses options passed to the script.
optionslongoptsoptindoptind parameter is present, then the
index where argument parsing stopped will be written to this variable.
The options parameter may contain the following
elements:
Note: Optional values do not accept " " (space) as a separator.
Note:
The format for the
optionsandlongoptsis almost the same, the only difference is thatlongoptstakes an array of options (where each element is the option) whereasoptionstakes a string (where each character is the option).
This function will return an array of option / argument pairs, 실패 시 FALSE를 반환합니다.
Note:
The parsing of options will end at the first non-option found, anything that follows is discarded.
| 버전 | 설명 |
|---|---|
| 7.1.0 |
Added the optind parameter.
|
| 5.3.0 | Added support for "=" as argument/value separator. |
| 5.3.0 | Added support for optional values (specified with "::"). |
| 5.3.0 |
Parameter longopts is available on all systems.
|
| 5.3.0 | This function is no longer system dependent, and now works on Windows, too. |
Example #1 getopt() example: The basics
<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>
shell> php example.php -fvalue -h
위 예제의 출력:
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
Example #2 getopt() example: Introducing long options
<?php
// Script example.php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values
$longopts = array(
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option
위 예제의 출력:
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
Example #3 getopt() example: Passing multiple options as one
<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac
위 예제의 출력:
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
Example #4 getopt() example: Using optind
<?php
// Script example.php
$optind = null;
$opts = getopt('a:b:', [], $optind);
$pos_args = array_slice($argv, $optind);
var_dump($pos_args);
shell> php example.php -a 1 -b 2 -- test
위 예제의 출력:
array(1) {
[0]=>
string(4) "test"
}