note 106885 added to function.getopt

From: Date: Thu, 15 Dec 2011 16:19:25 +0000
Subject: note 106885 added to function.getopt
Groups: php.notes 
Request: Send a blank email to php-notes+get-185078@lists.php.net to get a copy of this message
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) ?> ---- Server IP: 69.147.83.197 Probable Submitter: 24.127.190.210 ---- Manual Page -- http://www.php.net/manual/en/function.getopt.php Edit -- https://master.php.net/note/edit/106885 Del: integrated -- https://master.php.net/note/delete/106885/integrated Del: useless -- https://master.php.net/note/delete/106885/useless Del: bad code -- https://master.php.net/note/delete/106885/bad+code Del: spam -- https://master.php.net/note/delete/106885/spam Del: non-english -- https://master.php.net/note/delete/106885/non-english Del: in docs -- https://master.php.net/note/delete/106885/in+docs Del: other reasons-- https://master.php.net/note/delete/106885 Reject -- https://master.php.net/note/reject/106885 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185078) next »