getopt
getopt(string $short_options, array $long_options = [], int &$rest_index = null): array|false
CLI option parsing: a short-option string (colon = takes a value) plus a long-option table (trailing '=' = takes a value), returning an option-to-value map. Its modern successors are frameworks like argparse/flag/clap.
C C23
#include <getopt.h>
#include <stdio.h>
#include <string.h>
int main(void) {
/* getopt_long is the POSIX ancestor of PHP's getopt - feed it a fixed argv */
char a0[] = "tool", a1[] = "-v", a2[] = "--output", a3[] = "out.txt", a4[] = "input.txt";
char *argv[] = {a0, a1, a2, a3, a4, NULL};
int argc = 5;
int verbose = 0;
const char *output = "(none)";
static struct option longopts[] = {
{"verbose", no_argument, NULL, 'v'},
{"output", required_argument, NULL, 'o'},
{NULL, 0, NULL, 0},
};
optind = 1; /* reset the scan cursor so the parse starts at argv[1] */
int c;
while ((c = getopt_long(argc, argv, "vo:", longopts, NULL)) != -1) {
switch (c) {
case 'v': verbose = 1; break;
case 'o': output = optarg; break;
}
}
printf("verbose=%s\n", verbose ? "true" : "false");
printf("output=%s\n", output);
printf("positional=");
for (int i = optind; i < argc; i++) {
printf("%s%s", i > optind ? "," : "", argv[i]);
}
printf("\n");
return 0;
}
verbose=true output=out.txt positional=input.txt
C++ C++26
#include <iostream>
#include <string>
#include <vector>
int main() {
// std has no CLI parser; the loop below mirrors getopt("vo:", ...) rules
std::vector<std::string> argv = {"tool", "-v", "--output", "out.txt", "input.txt"};
bool verbose = false;
std::string output = "(none)";
std::string pos;
for (size_t i = 1; i < argv.size(); i++) {
const std::string& a = argv[i];
if (a == "-v" || a == "--verbose") {
verbose = true;
} else if (a == "-o" || a == "--output") {
output = argv[++i];
} else {
if (!pos.empty()) pos += ',';
pos += a;
}
}
std::cout << "verbose=" << (verbose ? "true" : "false") << '\n';
std::cout << "output=" << output << '\n';
std::cout << "positional=" << pos << '\n';
}
verbose=true output=out.txt positional=input.txt
C# v11.0.100
// std has no CLI parser (System.CommandLine is the modern one); rules mirror getopt("vo:", ...)
string[] argv = { "tool", "-v", "--output", "out.txt", "input.txt" };
bool verbose = false;
string output = "(none)";
var pos = new List<string>();
for (int i = 1; i < argv.Length; i++) {
string a = argv[i];
if (a is "-v" or "--verbose") verbose = true;
else if (a is "-o" or "--output") output = argv[++i];
else pos.Add(a);
}
Console.WriteLine($"verbose={verbose}");
Console.WriteLine($"output={output}");
Console.WriteLine($"positional={string.Join(",", pos)}");
verbose=True output=out.txt positional=input.txt
Go v1.27.4
package main
import (
"flag"
"fmt"
)
func main() {
// flag is Go's standard CLI parser; a FlagSet parses any slice like our fixed argv
fs := flag.NewFlagSet("tool", flag.ContinueOnError)
verbose := fs.Bool("v", false, "verbose mode")
output := fs.String("o", "", "output file")
fs.Parse([]string{"-v", "-o", "out.txt", "input.txt"})
fmt.Println("verbose:", *verbose)
fmt.Println("output:", *output)
fmt.Println("positional:", fs.Args())
}
verbose: true output: out.txt positional: [input.txt]
Java v27.0.1
public class Main {
public static void main(String[] args) {
// the std JDK has no CLI parser (picocli is the common choice); rules mirror getopt("vo:", ...)
String[] argv = {"tool", "-v", "--output", "out.txt", "input.txt"};
boolean verbose = false;
String output = "(none)";
StringBuilder pos = new StringBuilder();
for (int i = 1; i < argv.length; i++) {
String a = argv[i];
if (a.equals("-v") || a.equals("--verbose")) {
verbose = true;
} else if (a.equals("-o") || a.equals("--output")) {
output = argv[++i];
} else {
if (pos.length() > 0) pos.append(',');
pos.append(a);
}
}
System.out.println("verbose=" + verbose);
System.out.println("output=" + output);
System.out.println("positional=" + pos);
}
}
verbose=true output=out.txt positional=input.txt
JavaScript v26.13.1
// process.argv holds real CLI args at runtime; a fixed array demonstrates the parser rules
const argv = ["tool", "-v", "--output", "out.txt", "input.txt"];
let verbose = false;
let output = "(none)";
const pos = [];
for (let i = 1; i < argv.length; i++) {
const a = argv[i];
if (a === "-v" || a === "--verbose") verbose = true;
else if (a === "-o" || a === "--output") output = argv[++i];
else pos.push(a);
}
console.log(`verbose=${verbose}`);
console.log(`output=${output}`);
console.log(`positional=${pos.join(",")}`);
verbose=true output=out.txt positional=input.txt
PHP v8.6.0
// getopt() reads the real process argv, which `php -r` does not provide;
// the loop below mirrors getopt("vo:", ["verbose", "output="]) on a fixed argv
$argv = ["tool", "-v", "--output", "out.txt", "input.txt"];
$verbose = false;
$output = "(none)";
$pos = [];
for ($i = 1; $i < count($argv); $i++) {
$a = $argv[$i];
if ($a === "-v" || $a === "--verbose") {
$verbose = true;
} elseif ($a === "-o" || $a === "--output") {
$output = $argv[++$i];
} else {
$pos[] = $a;
}
}
echo "verbose=", var_export($verbose, true), PHP_EOL;
echo "output=$output", PHP_EOL;
echo "positional=", implode(",", $pos), PHP_EOL;
verbose=true output=out.txt positional=input.txt
Python v3.15.2
import argparse
# argparse is the modern successor of getopt; parse_args accepts any list
p = argparse.ArgumentParser(prog="tool")
p.add_argument("-v", "--verbose", action="store_true")
p.add_argument("-o", "--output")
p.add_argument("positional")
ns = p.parse_args(["-v", "--output", "out.txt", "input.txt"])
print(f"verbose={ns.verbose}")
print(f"output={ns.output}")
print(f"positional={ns.positional}")
verbose=True output=out.txt positional=input.txt
Rust v1.99.1
fn main() {
// std has no CLI parser (clap is the de-facto crate); rules mirror getopt("vo:", ...)
let argv = ["tool", "-v", "--output", "out.txt", "input.txt"];
let mut verbose = false;
let mut output = String::from("(none)");
let mut pos: Vec<&str> = Vec::new();
let mut i = 1;
while i < argv.len() {
match argv[i] {
"-v" | "--verbose" => verbose = true,
"-o" | "--output" => {
i += 1;
output = argv[i].to_string();
}
a => pos.push(a),
}
i += 1;
}
println!("verbose={verbose}");
println!("output={output}");
println!("positional={}", pos.join(","));
}
verbose=true output=out.txt positional=input.txt
TypeScript v26.13.1
// process.argv holds real CLI args at runtime; a fixed array demonstrates the parser rules
const argv: string[] = ["tool", "-v", "--output", "out.txt", "input.txt"];
let verbose: boolean = false;
let output: string = "(none)";
const pos: string[] = [];
for (let i = 1; i < argv.length; i++) {
const a: string = argv[i];
if (a === "-v" || a === "--verbose") verbose = true;
else if (a === "-o" || a === "--output") output = argv[++i];
else pos.push(a);
}
console.log(`verbose=${verbose}`);
console.log(`output=${output}`);
console.log(`positional=${pos.join(",")}`);
verbose=true output=out.txt positional=input.txt
Language differences
C: getopt/getopt_long are the ancestors of PHP's getopt (<getopt.h>); in the short-option string "vo:" a colon marks a required argument (two colons, optional); the long-option table pairs struct option with required_argument; optind is the scan cursor, optarg holds the value, and a leading ':' in the option string silences error printing and returns '?' instead.
C++: std has no CLI parser - hand-rolled loops (the example) or header-only libraries like CLI11/cxxopts.
C#: System.CommandLine is the modern official library carrying the getopt tradition; hand-rolled code iterates the top-level args (the real argv).
Go: the flag package is the standard - register with FlagSet.String/Bool then Parse; single and double dashes are equivalent (-v == --v), POSIX-style parsing needs the third-party pflag; the example parses a fixed slice via a FlagSet.
Java: std has no parser; picocli is the mainstream choice (annotations + automatic --help); hand-rolled loop in the example.
JavaScript: no standard library - hand-scan process.argv (the example); commander/yargs lead on npm.
PHP: getopt("vo:", ["verbose", "output="]) - a colon in the short string marks a required argument (two colons, optional), a trailing '=' in a long option marks one too; it returns ['v' => true, 'o' => '...'], and no-argument options yield false, NOT true (classic pitfall); no defaults/type coercion/usage generation - reach for symfony/console in complex CLIs; under php -r the real argv is unavailable, so the example replicates the rules on a fixed array.
Python: argparse is the modern counterpart - automatic -h/--help, type coercion, defaults, subcommands; parse_args accepts any list (the example); the old getopt/optparse modules survive but are superseded.
Rust: std has no parser and clap is the de-facto standard (derive macros generate --help automatically); hand-rolled loop in the example.
TypeScript: same as JavaScript; commander ships official type declarations.