Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass an array as a command line argument to a PHP script?

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?

like image 517
Manos Dilaverakis Avatar asked May 20 '10 10:05

Manos Dilaverakis


People also ask

Can we pass array as argument in 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);

How do I pass a command line argument to a PHP script?

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.

Can PHP be used for command line scripts?

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.

Can we use PHP to write command line scripts Yes?

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.


2 Answers

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" } */ 
like image 159
dev-null-dweller Avatar answered Sep 23 '22 06:09

dev-null-dweller


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.

like image 22
Dal Hundal Avatar answered Sep 23 '22 06:09

Dal Hundal