Parses options passed to the script.
Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (-). For example, an option string "x" recognizes an option -x. Only a-z, A-Z and 0-9 are allowed.
An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (--). For example, an longopts element "opt" recognizes an option --opt.
This function will return an array of option / argument pairs, or FALSE
on failure.
Note:
The parsing of options will end at the first non-option found, anything that follows is discarded.
Added support for "=" as argument/value separator.
Added support for optional values (specified with "::").
Parameter longopts
is available on all systems.
This function is no longer system dependent, and now works on Windows, too.
<?php // Script example.php $options = getopt("f:hp:"); var_dump($options); ?>
shell> php example.php -fvalue -h
The above example will output:
array(2) { ["f"]=> string(5) "value" ["h"]=> bool(false) }
<?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
The above example will output:
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) }
<?php // Script example.php $options = getopt("abc"); var_dump($options); ?>
shell> php example.php -aaac
The above example will output:
array(2) { ["a"]=> array(3) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(false) } ["c"]=> bool(false) }
$argv -
Please login to continue.