"php, pass parameters from command line to a php script" Answer’s


When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:

    var_dump($argc); //number of arguments passed 
    var_dump($argv); //the arguments passed

Like this:-

php script.php arg1 arg2 arg3

Will give the following output

array(4) {
  string(21) "d:Scriptsscript.php"
  string(4) "arg1"
  string(4) "arg2"
  string(4) "arg3"

See $argv and $argc for further details.

To do what you want, lets say

php script.php arg1=4

You would need to explode the argument on the equals sign:-

list($key, $val) = explode('=', $argv[1]);

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.

Wednesday, March 31, 2021
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :