20.2. Parsing Program Arguments with getopt

Problem

You want to parse program options that may be specified as short or long options, or they may be grouped.

Solution

Use PEAR’s Console_Getopt class. Its getopt( ) method can parse both short-style options such as -a or -b and long-style options such as --alice or --bob:

$o = new Console_Getopt;

// accepts -a, -b, and -c
$opts = $o->getopt($_SERVER['argv'],'abc');

// accepts --alice and --bob
$opts = $o->getopt($_SERVER['argv'],'',array('alice','bob'));

Discussion

To parse short-style options, pass Console_Getopt::getopt( ) the array of command-line arguments and a string specifying valid options. This example allows -a, -b, or -c as arguments, alone or in groups:

$o = new Console_Getopt;
$opts = $o->getopt($_SERVER['argv'],'abc');

For the previous option string abc, these are valid sets of options to pass:

% program.php -a -b -c
% program.php -abc
% program.php -ab -c

The getopt( ) method returns an array. The first element in the array is a list of all of the parsed options that were specified on the command line, along with their values. The second element is any specified command-line option that wasn’t in the argument specification passed to getopt( ). For example, if the previous program is run as:

% program.php -a -b sneeze

then $opts is:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => a
                    [1] => 
                )
            [1] => Array
                (
                    [0] => b
                    [1] => 
                )
        )
    [1] => Array
        (
            [0] => program.php
            [1] => sneeze
        )
)

Put a colon after an option in the specification ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.