note 106885 deleted from function.getopt by tularis
| From: | tularis@php.net | Date: | Fri, 16 Dec 2011 19:24:36 +0000 |
| Subject: | note 106885 deleted from function.getopt by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-185096@lists.php.net to get a copy of this message | ||
Note Submitter: Chris M.
Reason: bad code
----
Here's a useful function for getting parameters from command line (PHP 5.3+). The only
required parameter is the long name (by default it uses the first letter of the long name as the
short name). If the option is passed in two ways, the second takes precedence. If no value is
passed, a boolean is returned. If a numeric value is passed, an integer is returned. All other
values are interpreted as strings. See examples below the code.
<?php
function get_param($long, $short = null, $default = true)
{
$short = ($short ? $short : substr($long, 0, 1));
$options = getopt("$short::", array("$long::"));
// Option Not Set
if (empty($options)) {
return false;
}
// Get Value
end($options); // Use whichever was set last
$value = current($options);
if (ctype_digit($value)) {
$value = (int) $value;
}
$value = ($value ? $value : $default);
return $value;
}
?>
EXAMPLES:
<?php
// ./script.php -v
get_param('verbose'); // TRUE (bool)
// ./script.php --verbose
get_param('verbose'); // TRUE (bool)
// ./script.php
get_param('verbose'); // FALSE (bool)
// ./script.php -v1
get_param('verbose'); // 1 (int)
// ./script.php --verbose=1
get_param('verbose'); // 1 (int)
// ./script.php --verbose=yes
get_param('verbose'); // 'yes' (string)
// ./script.php -vnope --verbose=yep
get_param('verbose'); // 'yep' (string)
// ./script.php -s
get_param('verbose', 's', 'no'); // 'no' (string)
// ./script.php -syes
get_param('verbose', 's', 'no'); // 'yes' (string)
?>