PHP Edge Cases of getopt()


Example

This example shows the behaviour of getopt when the user input is uncommon:

getopt.php
var_dump(
    getopt("ab:c::", ["delta", "epsilon:", "zeta::"])
);
Shell command line
$ php getopt.php -a -a -bbeta -b beta -cgamma --delta --epsilon --zeta --zeta=f  -c gamma
array(6) {
  ["a"]=>
  array(2) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
  }
  ["b"]=>
  array(2) {
    [0]=>
    string(4) "beta"
    [1]=>
    string(4) "beta"
  }
  ["c"]=>
  array(2) {
    [0]=>
    string(5) "gamma"
    [1]=>
    bool(false)
  }
  ["delta"]=>
  bool(false)
  ["epsilon"]=>
  string(6) "--zeta"
  ["zeta"]=>
  string(1) "f"
}

From this example, it can be seen that:

  • Individual options (no colon) always carry a boolean value of false if enabled.
  • If an option is repeated, the respective value in the output of getopt will become an array.
  • Required argument options (one colon) accept one space or no space (like optional argument options) as separator
  • After one argument that cannot be mapped into any options, the options behind will not be mapped either.