Command Line Arguments in PHP

Command-line arguments are a common way to parameterize execution of programs. For example, php script.php uses script.php as an argument to the php program.

<?php

// The $argv array provides access to raw command-line arguments.
// Note that the first value in this array is the script name,
// and $argv[1] onwards holds the arguments to the program.
$argsWithProg = $argv;
$argsWithoutProg = array_slice($argv, 1);

// You can get individual args with normal indexing.
$arg = $argv[3];

print_r($argsWithProg);
print_r($argsWithoutProg);
echo $arg . "\n";

To experiment with command-line arguments, save this script and run it from the command line:

$ php command-line-arguments.php a b c d
Array
(
    [0] => command-line-arguments.php
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
c

In PHP, the $argv array contains all command-line arguments, including the script name. The array_slice() function is used to create a new array without the script name.

Next, we’ll look at more advanced command-line processing with option parsing libraries in PHP.