1. <?php
  2. /**
  3. * Decodes CLI arguments for an experiment.
  4. *
  5. * This script parses command-line arguments and stores them in an associative array.
  6. * It handles optional arguments with default values.
  7. */
  8. // Initialize an empty array to store the arguments.
  9. $args = [];
  10. // Use getopt to parse command-line arguments.
  11. // The options are:
  12. // -a: string - argument for setting the analysis type, default is "default".
  13. // -n: int - number of iterations, default is 10.
  14. // -v: bool - verbose mode, default is false.
  15. $opt = getopt("a:n:v", ["analysis:", "iterations:", "verbose"]);
  16. // Iterate through the parsed options.
  17. foreach ($opt as $key => $value) {
  18. // Handle short options (e.g., -a)
  19. if (strpos($key, ':') === false) {
  20. // Handle long options (e.g., --analysis)
  21. if (isset($value) && !empty($value)) {
  22. $args[$key] = $value; // Store the value of the option
  23. } else {
  24. // If a long option is specified but no value is provided, set it to true
  25. $args[$key] = true;
  26. }
  27. } else {
  28. // Handle options with values (e.g., -a string)
  29. list($shortOption, $value) = explode(':', $key, 2);
  30. if (isset($value) && !empty($value)) {
  31. $args[$shortOption] = $value; // Store the value of the option
  32. } else {
  33. $args[$shortOption] = true;
  34. }
  35. }
  36. }
  37. // Set default values if arguments are not provided.
  38. if (empty($args['analysis'])) {
  39. $args['analysis'] = 'default';
  40. }
  41. if (empty($args['iterations'])) {
  42. $args['iterations'] = 10;
  43. }
  44. if (empty($args['verbose'])) {
  45. $args['verbose'] = false;
  46. }
  47. // Output the decoded arguments (for debugging or logging).
  48. // echo "<pre>";
  49. // print_r($args);
  50. // echo "</pre>";
  51. // Now you can use the $args array to access the command-line arguments.
  52. // For example:
  53. // $analysisType = $args['analysis'];
  54. // $numIterations = $args['iterations'];
  55. // $isVerbose = $args['verbose'];
  56. ?>

Add your comment