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"
 }
 */
?>
read the predefined $argv array (Previous) Console_ProgressBar (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

Note by: roychri@php.net
The function condense_arguments() in this example removes all the non-options parameters (what comes after the last option and is not an option or what comes after --).

In order to preserve them, you can do:
$nonOptions = $params[1];

before calling condense_arguments().

Like this:

$params = $cg->getopt2($args, $shortopts, $longopts);
$nonOptions = $params[1];
$params = condense_arguments($params);


Also, the function condense_arguments() will discard duplicate options. For example, what if you want:

/path/script.php -f /path/file1 -f /tmp/file2

where file1 and file2 should both be accessible values in your script.
This new version below will handle it.

function &condense_arguments($params)
{
$new_params = array();
foreach ($params[0] as $param) {
if (isset($new_params[$param[0]])) {
if (!is_array($new_params[$param[0]])) {
$new_params[$param[0]] = (array)$new_params[$param[0]];
}
$new_params[$param[0]][] = $param[1];
}
else {
$new_params[$param[0]] = $param[1];
}
}
return $new_params;
}

Comments are welcome :)