[PHP] Read command-line options with getopt()

Created on November 30, 2026

Use getopt() to read short options such as -a and -b. A colon after an option name makes its value required.

Save this as sample.php.

<?php

$options = getopt('a:b:');
var_dump($options);

Run php sample.php -a Tom -b Alice.

array(2) {
  ["a"]=>
  string(3) "Tom"
  ["b"]=>
  string(5) "Alice"
}

Pass long options as an array in the second argument. Use an empty string for the short options if you only need long options.

<?php

$options = getopt('', ['alpha:', 'beta:']);
var_dump($options);

Run php sample.php --alpha Tom --beta Alice.

array(2) {
  ["alpha"]=>
  string(3) "Tom"
  ["beta"]=>
  string(5) "Alice"
}
PHP