Passing Arguments to Command-Line PHP

In a previous post we discussed how to tell whether or not you are on the command-line from within your PHP script. Today we’re going to talk about passing command-line arguments to your script. When on the command-line two variables are available to you, $argc and $argv. They are the argument count and argument vector, the former contains the number of arguments and the latter an array of the arguments. The name of the script is always present, so even when no arguments are passed in the count will be 1 and the array will contain the name of your script.

The following is a basic “Hello World” script (we’ll call it hello.php that takes the name from an argument and throws an error if no name is specified:

<?php

if ($argc != 2)
{
		exit('Usage: php -f hello.php <name>'
}
else
{
		exit('Hello ' . $argv[1] . '!'
}

?>

Now if the person running the script decides to specify more than a single name or no name at all they will be met with an error that contains usage instructions (like most command-line apps do). If they run the command correctly as php -f hello.php Josh they will be greeted with a very enthusiastic hello!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.