PHP Command Line Interface (CLI) Edge Cases of getopt()

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.


Got any PHP Question?