Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
I did it like this:
A slightly modified method found on the net:
function parseArgs( $_SERVER, $_REQUEST )
{
$out = array();
if ( is_array( $_SERVER ) && is_array( $_REQUEST ) )
{
$cli_args = isset( $_SERVER[ 'argv' ] ) ? $_SERVER[ 'argv' ] : array();
if ( count( $cli_args ) > 1 )
{
array_shift( $cli_args );
foreach ( $cli_args as $arg )
{
// --foo --bar=baz
if ( substr( $arg, 0, 2 ) == '--' )
{
$eqPos = strpos( $arg, '=' );
// --foo
if ( $eqPos === false )
{
$key = substr( $arg, 2 );
$value = isset( $out[ $key ] ) ? $out[ $key ] : true;
$out[ $key ] = $value;
}
// --bar=baz
else
{
$key = substr( $arg, 2, $eqPos - 2 );
$value = substr( $arg, $eqPos + 1 );
$out[ $key ] = $value;
}
}
// -k=value -abc
else if ( substr( $arg, 0, 1 ) == '-' )
{
// -k=value
if ( substr( $arg, 2, 1 ) == '=' )
{
$key = substr( $arg, 1, 1 );
$value = substr( $arg, 3 );
$out[ $key ] = $value;
}
// -abc
else
{
$chars = str_split( substr( $arg, 1 ) );
foreach ( $chars as $char )
{
$key = $char;
$value = isset( $out[ $key ] ) ? $out[ $key ] : true;
$out[ $key ] = $value;
}
}
}
// plain-arg
else
{
$value = $arg;
$out[] = $value;
}
}
}
else
{
if ( count( $_REQUEST ) > 0 )
{
foreach ( $_REQUEST as $key => $value )
{
$out[ $key ] = $value;
}
}
}
}
return $out;
}
$arguments = parseArgs( $_SERVER, $_REQUEST );
php myscript.php --firstarg=somedata -anotherarg=anotherdata --justaflag -anotherflag plainanarg
They are already in the array: $argv — Array of arguments passed to script
Head-on solution (for sure, it can be improved well):
<?php
$i = 0;
$params = array();
while (++$i < $argc) {
$arg = $argv[$i];
if (substr($arg, 0, 2) == '--') {
$key = substr($arg, 2);
} else if (substr($arg, 0, 1) == '-') {
$key = substr($arg, 1);
} else {
$params[] = $arg;
continue;
}
$i++;
$params[$key] = isset($argv[$i]) ? $argv[$i] : '';
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question