PHP args - How to read command line arguments in PHP

PHP command line args FAQ: How do I read command line arguments in PHP?

Answer: You just need to access the PHP argv array, as shown in this example:

#!/usr/bin/php
<?php
// loop through each element in the $argv array
foreach($argv as $value)
{
  echo "$value\n";
}
?>

If I save this file as argtest.php, and then run it, like this:

php argtest.php foo bar baz

I'll get the following output from the script:

argtest.php
foo
bar
baz

As you can see, the first argument is actually the name of your PHP script, which is consistent with many other languages that use this "ARGV" functionality. The other command line arguments are then shown after that.

Note that you can also access the PHP command line args as array elements, like this:

echo $argv[0];
echo $argv[1];

I hope this PHP command line arguments example is helpful. If you have any questions or comments, just use the form below.

Related command line arguments tutorials

For other tutorials on reading command line arguments from different programming languages, we have the following tutorials on our website:

Post new comment

The content of this field is kept private and will not be shown publicly.