Wednesday, November 9, 2016

[PHP] Convert command line parameters to array

When we write a script which will be run from command line, we may have a need to pass in certain input params. This is similar to the GET/POST parameters that a web page uses as input params.

The function below is an easy way to convert the command line input params and use it like an array in the script.

// Convert arguments to key/value pairs, like the $_GET or $_POST arrays
$args = array();
foreach ($argv as $arg) {
    if ($pos = strpos($arg, '=')) {
        $key = substr($arg, 0, $pos);
        $value = substr($arg, $pos+1);
        $args[$key] = $value;
    }
}

Input:
php run_my_script.php key1=value1 key2=value2 key3=value3

Output:
$args = [
    'key1' => value1,
    'key2' => value2,
    'key3' => value3,
];

No comments:

Post a Comment