Command-line argument parsing: Difference between revisions

Content deleted Content added
Tisane (talk | contribs)
PHP: a more useful example
Line 23:
 
===PHP===
[[PHP]] uses <code>argc</code> as a count of arguments and <code>argv</code> as an [[array (computing)|array]] containing the values of the arguments.<ref>{{cite web|url=http://php.net/manual/en/reserved.variables.argv.php |title=PHP Manual |publisher=PHP |date= |accessdate=2010-05-31}}</ref><ref>[[wikibooks:PHP Programming/CLI]]</ref> ForTo examplecreate an array from command-line arguments in the <code>-foo:bar</code> format, the following might be used:
 
<source lang="php">
var_dump$args = parseArgs( $argv );
echo getArg( $args, 'foo' );
 
function parseArgs( $args ) {
foreach( $args as $arg ) {
$tmp = explode( ':', $arg, 2 );
if( $arg[0] == "-" ) $args[ substr( $tmp[0], 1 ) ] = $tmp[1];
}
return $args;
}
 
function getArg( $args, $arg ) {
if( isset( $args[$arg] ) ) {
return $args[$arg];
}
return false;
}
</source>