Generate a command line arg string from an associative array.
This is purely built for functionality, not for beauty: no grouping of shorthand flags, all args will be escaped and wrapped in single quotes, no matter if needed or not.
Associative key-value pairs will be treated as command line options while array entries with no/integer keys will be used as regular arguments.
echo 'node ' . generateArgStr([
'app.js',
'arg' => 'foo'
]);
// node 'app.js' '--arg' 'foo'Command line options will be prefixed with two dashes -- for regular options and one dash - for short options (option names with just one character).
echo 'node ' . generateArgStr([
'e' => 'console.log("foo")'
]);
// node '-e' 'console.log("foo")'You can change this behaviour by passing the prefix option.
It defaults to this array: [ 'short' => '-', 'long' => '--' ] but you can also just pass a string:
echo 'node ' . generateArgStr([
'e' => 'console.log("foo")'
], [
'prefix' => '--'
]);
// node '--e' 'console.log("foo")'Associative pairs with boolean values will be present as simple flag options (if value is true) or completely be omitted (if value is false). This allows for easy conditional toggling of options.
echo 'node ' . generateArgStr([
'inspect' => false,
'app.js',
'verbose' => true
]);
// node 'app.js' '--verbose'By default, options and their values will be separated by a space and thus be two technically sepearate arguments. However, some CLI apps need a different kind of option formatting, like mysql — it requires options and their according values as one argument, joined by an "equals" sign =.
For that, there's the glue option:
echo 'mysql ' . generateArgStr([
'user' => 'root'
], [
'glue' => '='
]);
// mysql '--user=root'