TL;DR: $argv
is an array of arguments passed to the script with the first index being the name of the script itself. And $argc
is the number of arguments passed to the the script (which will always at least be 1
).
Arguably, pun intended, one of the key pieces of command-line application is making sure that they are interactive through command-line arguments. In PHP, there are two variables to understand:
$argc
is the number of arguments passed to script. Note the script’s filename is always passed as an argument to the script, therefore the minimum value of$argc
is1
.$argv
is an array of arguments passed to script. Note the first argument$argv
is always the name that was used to run the script.
Command-Line Arguments
So if you take the content provided in the previous post on drafting a script you could write something like this:
#!/usr/local/bin/php
<?php
echo "**********\n";
echo "The number of arguments passed to script: $argc.\n";
echo "The array of arguments passed to the script:\n";
print_r( $argv );
echo "**********\n";
And the output should show:
The number of arguments passed to the script: 1. The array of arguments passed to the script is: Array ( = start.php )
From here, it’s worth experimenting with arguments such as:
$ ./start.php --foo --bar script=foo
An Important Note on Characters and Front-Ends
One important thing to note is that this is following standard form for command-line arguments. I don’t advise trying to throw extra characters into the mix (especially something like ;
which can cause the script to terminate its execution).
Further, the above format makes it easy to parse the information from the command-line and verify it however you see fit. Additionally, it allows you to pass those arguments into other functions or class that can be presented in a web application, WordPress front-end, or some other type of GUI (such as one that uses a REST endpoint).