Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active January 9, 2019 13:44
Show Gist options
  • Select an option

  • Save loilo/87a2237bcaf7f0bc4d7ab5b53f6634a8 to your computer and use it in GitHub Desktop.

Select an option

Save loilo/87a2237bcaf7f0bc4d7ab5b53f6634a8 to your computer and use it in GitHub Desktop.
Minimist-like PHP $argv parser

This snippet allows for very simple argument parsing. Use it like

$args = require_once 'args.php';

Features:

  • arguments in quotes are handled correctly
  • long names: php app.php --name foo$args['name'] === "foo"
  • short names: php app.php -n foo$args['n'] === "foo"
  • values without names: php app.php foo bar$args['_'] === [ "foo", "bar" ]
  • names without subsequent values are booleans (true): php app.php --name$args['name'] === true
  • combined short names are always booleans (true): php app.php -wvb$args['w'] === true, $args['v'] === true, $args['b'] === true

Non-Features:

No error handling at all. Being in a CLI environment is assumed and arguments are trusted to be well-formatted.

<?php
$args = array_slice($argv, 1);
$unnamedArgs = [];
$namedArgs = [];
$currentArg = null;
foreach ($args as $arg) {
// Long name
if (substr($arg, 0, 2) === '--') {
// Boolean arg if no value is given
if (!is_null($currentArg)) {
$namedArgs[$currentArg] = true;
}
$currentArg = substr($arg, 2);
// Short name(s)
} elseif (substr($arg, 0, 1) === '-') {
// Boolean arg if no value is given
if (!is_null($currentArg)) {
$namedArgs[$currentArg] = true;
}
// One short name = await value
if (strlen($arg) === 2) {
$currentArg = substr($arg, 1);
// Multiple short names = all booleans
} else {
for ($i = 1; $i < strlen($arg); $i++) {
$namedArgs[$arg[$i]] = true;
}
}
// Unnamed
} else {
// Set for last arg name
if (!is_null($currentArg)) {
$namedArgs[$currentArg] = $arg;
$currentArg = null;
// Set as unnamed arg
} else {
$unnamedArgs[] = $arg;
}
}
}
// If there's an open named arg, make it true
if ($currentArg) $namedArgs[$currentArg] = true;
return array_merge([ '_' => $unnamedArgs ], $namedArgs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment