Advertisement
Beginner PHP, PHP CLI Scripting

How do you access command line arguments passed to a PHP script using the $argv and $argc superglobals?

Short answer

The $argv superglobal is an array containing every argument passed to the script from the command line, with the first element always being the script's own file name, and $argc contains the total count of those arguments, together letting your script read and respond to…

Save PHP mock interview
Advertisement
AModel answer
The $argv superglobal is an array containing every argument passed to the script from the command line, with the first element always being the script's own file name, and $argc contains the total count of those arguments, together letting your script read and respond to whatever specific arguments were provided when it was invoked, similar to how a web script reads data from $_GET or $_POST.
// Running: php greet.php Ali
echo "Script name: $argv[0]";
echo "First argument: $argv[1]";
echo "Total arguments: $argc";
Real-world example
A backup script reads the target directory to back up directly from a command line argument, letting the same script be reused flexibly for different directories simply by changing the argument provided each time it is run.
Likely follow-ups
  • How do you provide default values for optional command line arguments that were not supplied?
  • What is the difference between $argv and using PHP's more structured getopt function?
Related topics