Skip to content
Advertisement

How can I parse command line arguments in PHP?

I call a PHP script from command line $ php my_script.php --num1=124 --first_name=don

How can I get access to any key value pairs passed into this script? The keys can be arbitrary, so using getopt() with particular values will not work.

Here is what I want access to in my script:

$my_args = array(
  "num1" => 124,
  "first_name" => "don"
);

If I use var_dump($argv), I get this output:

array(
  [0] => "my_script.php",
  [1] => "--num1=5",
  [2] => "--num2=123"
);

Should I just look

Advertisement

Answer

$my_args = array();
for ($i = 1; $i < count($argv); $i++) {
    if (preg_match('/^--([^=]+)=(.*)/', $argv[$i], $match)) {
        $my_args[$match[1]] = $match[2];
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement