tags:

views:

301

answers:

1

I'm using Console_Getopt in PHP 5.2, and finding it surprising about how different it is from getopt in other languages (perl, bash, java). Can anyone recommend how to parse the args from the array "$opts" returned?

php myprog.php -a varA -c -b varB

$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r($opts);

// the print_r returns below

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => a
                    [1] => varA
                )

            [1] => Array
                (
                    [0] => c
                    [1] =>
                )

            [2] => Array
                (
                    [0] => b
                    [1] => varB
                )

        )

    [1] => Array
        (
        )

)

I started doing something like below, which is long-winded, so I'm looking for suggestions on dealing with command-line flags in php.

foreach($opts[0] as $i -> $keyval) {
    list($key, $val) = $keyval;
    if($key == 'a') {
        print "valueForA: $val\n";
    } else if($key == 'b') {
        print "valueForB: $val\n";         
    } else if($key == 'c') {
        print "c is set\n";
    }
}

I wonder why PHP's getopt isn't like perl's, where the array's key is the flag eg $opts{'a'} .. that would be convenient.

+1  A: 

Per the inline documentation

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.

Which means you easily discard the second array, and assume a commitment to the keeping the array of arrays, first element option, second element value, format.

With that assumption in place, try

$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r(getHashOfOpts($opts));

function getHashOfOpts($opts) {
 $opts = $opts[0];
 $return_opts = $opts;
 $return_opts = Array();
 foreach($opts as $pair){
  $return_opts[$pair[0]] = $pair[1];
 }
 return $return_opts;
}

to get an data structure more of your liking.

As for why this is different than other implementation of getopt, ask the maintainers.

Alan Storm