
Wikis & learning
Read command-line arguments with defaults
A PHP script launched from the command line receives its own filename as its first argument. The first user-provided value comes next.
A PHP script launched from the command line receives its own filename as its first argument. The first user-provided value comes next.
Walkthrough
The helper accepts an array shaped like argv. A default name lets the script run without extra arguments. Checking the array independently makes command-line behavior straightforward to test.
PHP example
<?php
function greeting(array $arguments): string {
return 'Hello, ' . ($arguments[1] ?? 'reader');
}
echo greeting(['welcome.php']), PHP_EOL;
echo greeting(['welcome.php', 'Sam']);Expected output
Hello, reader
Hello, SamChange and check
Call the helper with just the script filename, then add a second word. Decide how your application should handle more than one argument.
Discussion
Sign in to participate.



