Parsing Named Arguments in PHP CLI Scripts
When you execute a PHP script from the command line, the environment provides access to arguments via the global $argv array or the shorter $_SERVER['argv']. A basic implementation, such as reading the first positional argument like this:
$name1 = $argv[1];
echo $name1;
works perfectly for simple scenarios where the order of data points matters. However, relying strictly on position becomes problematic as scripts grow in complexity. You quickly run into ambiguity when a user needs to specify multiple inputs, such as a first name and a last name, without knowing which array index corresponds to which value.
To enforce a specific structure and improve user experience, you want to accept named arguments like -inputFirstName="Robby". This approach mirrors the flexibility of configuration files or environment variables while retaining the immediacy of command-line execution. Parsing these flags requires iterating through $argv to identify keys starting with a dash and extracting their associated values.
A robust pattern involves looping through every element in $argv. You check if an element starts with a hyphen (-). If it does, you strip the prefix to create a key (e.g., inputFirstName) and then look for the subsequent non-flag argument as its value. This logic naturally handles the separation between the flag definition and the data payload.
Here is a practical implementation using a simple parser:
<?php
$inputs = [];
foreach ($argv as $index => $arg) {
if (strpos($arg, '-') === 0) {
$key = substr($arg, 1); // Remove the leading '-'
// Check if there is a next argument and it doesn't start with '-'
if (isset($argv[$index + 1]) && strpos($argv[$index + 1], '-') !== 0) {
$inputs[$key] = $argv[$index + 1];
$index++; // Skip the next element as it is the value we just consumed
}
}
}
// Accessing values
echo "First Name: " . ($inputs['inputFirstName'] ?? 'Not provided') . PHP_EOL;
echo "Last Name: " . ($inputs['inputLastName'] ?? 'Not provided') . PHP_EOL;
This method is stateless and requires no external libraries, making it ideal for small utility scripts or quick prototypes. It also gracefully handles missing values by using the null coalescing operator (??), preventing undefined index notices.
However, this manual parsing approach has limitations regarding strictness. If a user accidentally types --inputFirstName=Robby (with an equals sign) instead of separating the flag and value with a space, this specific loop will fail to parse it correctly because it expects two distinct array elements. To handle both spacing styles (-key value and -key=value) in a single pass, you can add a conditional check inside the loop:
if (strpos($arg, '-') === 0) {
// Handle -key=value style
if (strpos($arg, '=') !== false) {
$parts = explode('=', $arg, 2);
$key = substr($parts[0], 1);
$value = $parts[1];
} else {
// Handle -key value style
if (isset($argv[$index + 1]) && strpos($argv[$index + 1], '-') !== 0) {
$key = substr($arg, 1);
$value = $argv[$index + 1];
} else {
$value = null;
}
}
$inputs[$key] = $value ?? '';
}
While writing a custom parser works for many use cases, you must weigh this against the complexity of your application. If your script needs to handle complex types, validation, or help text generation, building a parser from scratch can become error-prone. In large-scale applications, especially those built on modern frameworks, leveraging existing solutions is often safer. The LaravelCompany ecosystem, for instance, frequently utilizes packages like illuminate/console which provide robust argument parsing capabilities out of the box, handling edge cases and type coercion automatically.
Ultimately, the choice depends on your project's scale. For a standalone utility script, the custom loop offers full control with zero dependencies. For enterprise applications where consistency and validation are paramount, integrating a dedicated parser or framework component is the professional standard.