I am writing a PHP script and should get some parameters (h, n and v). For me, the best way to get this is to use a function getopt. Also, if an unexpected option is passed, I would like to display a help message. However, the function getoptreturns only expteced options.
Here is my script:
$options = getopt('hnv');
if (!empty($options)) {
foreach (array_keys($options) as $option) {
switch ($option) {
case 'n':
case 'v':
break;
case 'h':
self_usage();
exit(0);
default:
self_usage('Too many params');
exit(1);
}
}
}
But if I run my script with an unexpected parameter, for example -p, it starts because the array of options is empty.
php myscript.php -p
If I pass an unexpected option with the expected, it will also start.
php myscript.php -pn
php myscript.php -p -n
I tried to check the count of arguments passed, but this only works if I pass the arguments one by one ( -n -p), and not all in one ( -np).
if ((count($argv) - 1) > count($options)) {
self_usage();
}
Is there a good way to check for non-excluded options in this case?
!