I'm maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I've just fixed a bug that would not allow it to fetch array variables from POST and GET and I'm wondering whether this is also applicable to the part that deals with the command line.
Can you pass an array as a command line argument to PHP?
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);
To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.
As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.
Yes, we can create a command-line PHP script as we do for web script, but with few little tweaks. We won't be using any kind of HTML tags in command-line scripting, as the output is not going to be rendered in a web browser, but displayed in the DOS prompt / Shell prompt.
Directly not, all arguments passed in command line are strings, but you can use query string as one argument to pass all variables with their names:
php myscript.php a[]=1&a[]=2.2&a[b]=c <?php parse_str($argv[1]); var_dump($a); ?> /* array(3) { [0]=> string(1) "1" [1]=> string(3) "2.2" ["b"]=>string(1) "c" } */
Strictly speaking, no. However you could pass a serialized (either using PHP's serialize()
and unserialize()
or using json) array as an argument, so long as the script deserializes it.
something like
php MyScript.php "{'colors':{'red','blue','yellow'},'fruits':{'apple','pear','banana'}}"
I dont think this is ideal however, I'd suggest you think of a different way of tackling whatever problem you're trying to address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With