array getopt ( string options [, array long_options])
Being able to accept parameters into your scripts with argc and argv is good enough for some people, but if you run on Unix there's an even better way: the getopt() function. With getopt() you just tell it what parameters your script is able to accept, and it does the rest.
Author's Note: getopt() doesn't work on Windows. You might try using the Console_GetOpt package from PEAR, available from http://pear.php.net/package/Console_Getopt
Here's a basic example:
<?php $options = getopt("abc"); var_dump($options); ?>
That code tells getopt() to read in three parameters from the command line: -a, -b, and -c. If any of these are specified, they are placed into the array return value. Those that are not specified are simply left out of the array. Any extra parameters that were passed that aren't listed get ignored.
So, try running that script like this:
php getopt.php -a -b -d
That should output the following:
As you can see, as "c" wasn't specified and "d" wasn't asked for, neither of them make it into the returned array.
Of course, just knowing the "a" and "b" are set isn't very interesting - getopt() can also track values that parameters are set to. Change the script to this:
<?php $options = getopt("ab:cd:"); var_dump($options); ?>
Note that I've changed the parameter passed to getopt() - there are now two colons in there, and we also accept a "d" parameter. What the two colons do is say that the parameter before expects to get some value attached to it. So, we can now call the script like this:
php getopt -a -b hello -d world
This time we only get "false" an array value when there was no value passed:
There is one potential gotcha here, and that's the fact that the function isn't smart enough to allow optional values. Try calling the script like this:
php getopt -a -b -d world
There is a second parameter you can pass to getopt(), which is an array specifying the names of long parameters (that is, --foo rather than just -f) to accept. Sadly the functions behind it only work on a small number of systems; my test Linux boxes didn't work at all!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Getting down and dirty >>
Previous chapter: Your first CLI script
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.