Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What are command-line arguments in PHP?

Dario Vincenzo Tarantini

PHP is a fully-featured language with the capability to parse command-line arguments. This is useful when we need to create some sort of shell script to handle different scenarios based on a certain input.

Unlike other C-like languages, we don’t have to declare anything to handle command-line arguments because PHP itself comes with two built-in variables, $argv and $argc:

  • $argv: an array of all the arguments passed to the script
  • $argc: the number of arguments passed to the current script

Note: These variables are not available when register_argc_argv is disabled.

How to parse cli arguments

We can easily parse arguments that access the variables above.

Note: The first element of $argv is always the name of the script.

For example, if we want to parse the first element, we can use the code below:

<?php 
if ($argc == 2){
    echo $argv[1];
} else {
    echo "Please, provide *exactly* one argument.\n";
}

In this code, we check that the number of the arguments is exactly two, and print the first parameter after that.

Note that we print the second element since the first is the script name.

If we call the function as follows:

$ php-cli main.php hello

The expected output is:

hello%

RELATED TAGS

php
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring