PHP $argc

The $argc variable is a PHP superglobal that stores the count of command−line arguments passed to a script. It is only available when running PHP scripts from the command line, not through a web server. The minimum value is 1 since the script filename itself counts as an argument.

Note: This variable requires the register_argc_argv directive to be enabled in php.ini (enabled by default).

Syntax

The $argc variable is automatically populated when running PHP from command line ?

<?php
echo $argc; // Number of command-line arguments
?>

Example

Here's a script that validates the number of command−line arguments ?

<?php
if ($argc != 3) {
    echo "Error: Expected exactly 2 arguments (plus script name)<br>";
    echo "Usage: php script.php arg1 arg2<br>";
    die();
} else {
    echo "Valid number of arguments: $argc<br>";
    echo "Script received the correct parameters.<br>";
}
?>

Output

Running with incorrect number of arguments ?

C:\php>php test.php arg1 arg2 arg3
Error: Expected exactly 2 arguments (plus script name)
Usage: php script.php arg1 arg2

Running with correct number of arguments ?

C:\php>php test.php arg1 arg2
Valid number of arguments: 3
Script received the correct parameters.

Key Points

Aspect Details
Minimum Value 1 (script name counts)
Availability Command line only
Type Integer
Related Variable $argv (argument values)

Conclusion

The $argc variable is essential for validating command−line input in PHP CLI scripts. Use it alongside $argv to create robust command−line applications that handle user input properly.

Updated on: 2026-03-15T09:25:52+05:30

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements