views:

158

answers:

3

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?

+4  A: 

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.

Mailslut
It is `unserialize()` not `deserialize()`
dev-null-dweller
@dev-null-dweller, thanks - amended.
Mailslut
+1  A: 

You need to figure out some way of encoding your array as a string. Then you can pass this string to PHP CLI as a command line argument and later decode that string.

Salman A
+1  A: 

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"
}
*/
dev-null-dweller