Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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_argvdirective 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.
