Current Location: Home> Latest Articles> How to Get and Process Command Line Arguments in PHP

How to Get and Process Command Line Arguments in PHP

gitbox 2025-07-14

Using argc and argv Global Variables

In PHP, you can retrieve command line arguments using two global variables: argc and argv. argc represents the number of command line arguments, while argv is an array that holds all the command line arguments. argv[0] is the script name itself.


$argc // Number of command line arguments
$argv // Array of command line arguments

For example, running the following command:


php script.php arg1 arg2 arg3

In your script, you can retrieve the arguments with the following code:


$argc // Outputs 4 (including the php command itself)
$argv // Outputs ['script.php', 'arg1', 'arg2', 'arg3']

Getting Specific Command Line Arguments

If you need to access a specific command line argument, you can do so by using the array index. For instance, to get the first argument, arg1:


$arg1 = $argv[1]; // 'arg1'

Remember that array indexing starts at 0, so $argv[0] represents the script itself.

In real-world applications, you can use an if statement to check the number of command line arguments and ensure you're receiving the expected ones. For example:


if ($argc != 4) {
    echo "Usage: php script.php arg1 arg2 arg3
";
    exit(1);
}
$arg1 = $argv[1];
$arg2 = $argv[2];
$arg3 = $argv[3];

This code ensures that there are exactly four command line arguments, otherwise it will output a usage message and exit.

Handling Command Line Arguments

Once the command line arguments are retrieved, you can execute different actions based on their values. For example, you can run different logic depending on the argument passed:


if ($arg1 == "run") {
    // Execute an action
} elseif ($arg1 == "stop") {
    // Execute another action
} else {
    echo "Invalid argument: $arg1
";
    exit(1);
}

The above code checks the value of $arg1. If it is "run", a specific action is executed; if it is "stop", another action is triggered; otherwise, it outputs an error message and exits.

Conclusion

By using the argc and argv global variables in PHP, you can easily retrieve and process command line arguments, and execute different operations based on those arguments. This allows for more flexible and scalable PHP scripts in a command line environment.