Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created April 28, 2022 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/bf75828758cc6fbde7eaa43a7476dd02 to your computer and use it in GitHub Desktop.
Save kobus1998/bf75828758cc6fbde7eaa43a7476dd02 to your computer and use it in GitHub Desktop.
parse argv arguments
<?php
(new class {
public function __invoke()
{
$aArgs = $this->parseArgv($GLOBALS['argv']);
var_dump($aArgs);
die("\n");
}
/**
* parse argv
*
* --option=val
* -flag
* param
*
* @param array $aArgs
* @return array
*/
public function parseArgv($aArgs)
{
$iParams = 0;
$aResult = [
'options' => [],
'flags' => [],
'params' => []
];
foreach ($aArgs as $sArg) {
if (strpos($sArg, '--') !== false) {
list($sKey, $sVal) = explode('=', $sArg);
$aResult['options'][trim($sKey, '--')] = $sVal;
} elseif (strpos($sArg, '-') !== false) {
$aResult['flags'][] = trim($sArg, '-');
} else {
$aResult['params'][$iParams] = $sArg;
$iParams++;
}
}
return $aResult;
}
})();
die("\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment