Examples
The following example shows how to setup short and long option arrays as well as reading the arguments passed via commandline. The example also introduces a helper method that converts the parsed parameters returned by Console_Getopt into a key-value-array.
<?php
/**
* Example how to get a key-value pair array
* from command line parameters with Console_Getopt.
*
* @link http://pear.php.net/bugs/bug.php?id=13902
*/
require_once 'Console/Getopt.php';
/**
* Make a key-value array.
* Since Console_Getopt does not provide such a method,
* we implement it ourselves.
*
* @params array $params Array of parameters from Console_Getopt::getopt2()
*
* @return array key-value pair array
*/
function &condense_arguments($params)
{
$new_params = array();
foreach ($params[0] as $param) {
$new_params[$param[0]] = $param[1];
}
return $new_params;
}
$cg = new Console_Getopt();
$args = $cg->readPHPArgv();
array_shift($args);
$shortOpts = 'u:g:';
$longOpts = array('user=', 'group=');
$params = $cg->getopt2($args, $shortOpts, $longOpts);
if (PEAR::isError($params)) {
echo 'Error: ' . $params->getMessage() . "\n";
exit(1);
}
var_dump(condense_arguments($params));
/*
When called as follows:
associative.php -u jason -g argonauts
you will get this output:
array(2) {
["u"]=>
string(5) "jason"
["g"]=>
string(9) "argonauts"
}
*/
?>