Introduction - Options

Introduction - Options – Defining and processing options

Defining options

Getopt() supports two types of options: short options and long options

Calling a script with short and long options

# Using short options
myphpscript -q -l en -o
# Using long options instead
myphpscript --quite --lang=en --option
# Mixing both
myphpscript -q --lang=en -o

You have to define which options you want to support. The second argument of getopt() requires a string containing all supported chars. For the example above this would be at least:

<?php
$shortoptions 
"qlo";
?>

The order of the characters is not important. Often you have to define options with (optional) parameters. To express that a option requires a parameter, you have to add a colon. If the parameter is optional, add a double colon, ie:

<?php
$shortoptions 
"ql:o::";
?>

this means the following script calls are permitted, ie.

myphpscript myphpscript -q myphpscript -q -l en myphpscript -o text myphpscript -o

whilst

myphpscript -l

is not permitted. The -l option requires a parameter, if the option is used.

The long options work equally, but they have to be defined in an array:

<?php
$longoptions 
= array("quite""lang""option");
?>

For defining optional parameters, use '=' and '==' like the colon in short options.

<?php
$longoptions 
= array("quite""lang=""option==");
?>

The returned options array

The return value is an array of two elements: the list of parsed options and the list of non-option command-line arguments. Each entry in the list of parsed options is a pair of elements - the first one specifies the option, and the second one specifies the option argument, if there was one, else the value is NULL.