Databases Reference
In-Depth Information
5 The Stone Roses
6 Kylie Minogue
Using Command-Line Arguments
You can pass arguments to PHP scripts from the command line. You can use command-
line arguments to modify the behavior of a program, or to provide information. The
$argc variable indicates the count of the arguments passed, and the $argv array contains
the argument values. The first entry in the $argv array ( $argv[0] ) is always the command
that was used to run the script. The second entry in this array ( $argv[1] ) is the first
argument typed in after the command name. The third entry ( $argv[2] ) is the second
argument, and so on. This means that the the number of values in the $argv array will
always be one more than the number of arguments typed after the command. If one
argument is entered, the count will be 2.
Let's modify our hello.cl.php script to use command-line arguments, as shown in Ex-
ample 14-7.
Example 14-7. PHP command-line program that prints a message using the first command-line
argument
#!/usr/bin/php
<?php
if($argc==2)
echo "Hello, {$argv[1]}!\n";
else
echo "Syntax: {$argv[0]} [Your First Name]\n";
?>
To use any number of entered arguments rather than just one, Example 14-8 uses the
foreach( ) function to iterate over every argument. For each entry in the $argv array,
the $index => $argument construct places the entry index (also known as the key) in
the $index variable, and the entry value in the $argument variable. If the index is not
zero, we print out the value. We don't print the value for index zero, as that is the name
of the command itself. Notice how we've included a space before each argument, and
how we add an exclamation mark and newline after all the arguments have been
printed.
Example 14-8. PHP command-line program that prints a message using all the provided command-
line arguments.
#!/usr/bin/php
<?php
if($argc==1)
echo "Syntax: {$argv[0]} [Your Name]\n";
else
{
echo "Hello";
foreach($argv as $index => $argument)
if($index!=0)
 
Search WWH ::




Custom Search