PHPackages                             tests-always-included/option-parser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. tests-always-included/option-parser

ActiveLibrary[CLI &amp; Console](/categories/cli)

tests-always-included/option-parser
===================================

Command-line option parser similar to getopt

0.1.4(11y ago)014MITPHPPHP &gt;=5.3

Since Sep 22Pushed 11y ago6 watchersCompare

[ Source](https://github.com/tests-always-included/option-parser-php)[ Packagist](https://packagist.org/packages/tests-always-included/option-parser)[ Docs](https://github.com/tests-always-included/option-parser-php/)[ RSS](/packages/tests-always-included-option-parser/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (3)Used By (0)

`OptionParser` - PHP Version
============================

[](#optionparser---php-version)

`OptionParser` is a library to help you parse command-line options, similar to how `getopt()` works. An effort is made to make it POSIX compliant and easy for people to use. Features of many other implementations have been integrated in order to provide significant flexibility and to make it easier to use.

There is a sample parser in the [examples](examples/) directory.

[![Build Status](https://camo.githubusercontent.com/502429eccbde30ef60e880f28d940f2d56d3287d84a59948c6f82d266e413e9a/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f74657374732d616c776179732d696e636c756465642f6f7074696f6e2d7061727365722d7068702e706e67)](http://travis-ci.org/tests-always-included/option-parser-php)

Features
--------

[](#features)

- -x (short options)
- -xxxyxxz (combined and repeating short options)
- --long (long option)
- -x=Value, --long=Value (optional and required values)
- -xValue --long Value (special format for required values)
- -- (signify the end of options)
- Nearly automatic help generation
- Can stop on the first unparsed option
- Can autocomplete long options
- Returns unparsed options
- Flexible option handling

How to use
----------

[](#how-to-use)

First, create the parser object:

```
$parser = new OptionParser();

```

Next, you add some options. I'll jump right in and add the standard "help" option, triggered with either "-h" or "--help".

```
$parser->addOption('h', 'help', 'Display this help message')
    ->action($parser->helpAction());

```

Finally, parse the command line options.

```
$parser->parse();

```

How To Use Parameters
---------------------

[](#how-to-use-parameters)

The whole point of the library is to make it really easy to handle the parsing of options to your program. Let's run through a few examples here:

### Toggle a Flag With A Callback

[](#toggle-a-flag-with-a-callback)

In PHP you can pass more than just callbacks; names of functions, an array with the class name and method, and anything else that works with `call_user_func()`. Let's have this option only work with the short option "-f".

```
$flagWasSet = false;

$parser->addOption('f', null, 'Toggle a flag')
    ->action(function () use (&$flagWasSet) {
        $flagWasSet = true;
    });

```

### Pass a Required Value

[](#pass-a-required-value)

Many options need a specific value, such as an input file to process. Here is another option that is specified by "-i" or "--input" that requires a filename of the input file. It uses a callback, just like the above example.

```
$inputFile = 'php://stdin';

$parser->addOption('i', 'input', 'Specify an input file')
    ->argument('FILE')  // You can name the argument anything you like
    ->action(function ($value) use (&$inputFile) {
        $inputFile = $value;
    });

```

### Optional Value and Parameter Object

[](#optional-value-and-parameter-object)

Closures in PHP are not quite the same as JavaScript since you need to explicitly list the variables that are in scope for the execution of the function. An alternative would be to use the returned object from setting up the option on the parser. Here, we add a debug option that lets you set the debug level, but can default to 5 if you don't set one explicitly.

```
$debugLevel = 0;

$debugOption = $parser->addOption(null, 'debug',
     'Sets the debug level; if set, default is 5')
    ->argument('Level', false);  // See note below

// Don't forget to set up the other options here

$parser->parse();

// Now use the $debugOption object to set the debug value
if ($debugOption->count()) {
    $debugLevel = $debugOption->value() || 5;
}

```

The first parameter to `OptionParameter->argument()` is the name of the parameter, as seen in the generated help message. It doesn't affect the execution of the parser in any other way. The second parameter, `false`, makes the argument optional.

`$debugOption->count()` returns the number of times the argument was specified. `$debugOption->value()` returns the last value passed to the parameter. For detailed information, check out the documentation for [OptionParameter](option-parameter.md).

Named Parameters
----------------

[](#named-parameters)

Keeping references to the objects can be tedious. Here is the above example altered to name the parameter and then use the named parameter. I'm naming the parameter "dddd" to help contrast against the previous code.

```
$debugLevel = 0;

$parser->addOption(null, 'debug',
     'Sets the debug level, default is 5', 'dddd')
    ->argument('Level', false);

// Don't forget to set up the other options here

$parser->parse();

if ($parser->dddd->count()) {
    $debugLevel = $parser->dddd->value();
}

```

Getopt
------

[](#getopt)

Lastly, PHP has a unique format for handling command-line arguments using the built-in function `getopt()`. After setting up options and calling `$parser->parse()`, you can get back an array that mimics `getopt()`'s return value. This should make it easier to plug this parser into your code and benefit from the better option handling without retooling anything after the call to `getopt()` that you'd normally make.

```
// Set up options and then call parse()
$parser->parse();

// Get back an array of options like PHP's getopt()
$options = $parser->getopt();

```

Unparsed Options
----------------

[](#unparsed-options)

If you plan on making a program that takes a list of files or needs to work on the options that were passed to the program but were not parsed by `OptionParser`, that's really simple:

```
$unparsed = $parser->parse();

```

This will contain an array of options, split out into individual options. If you passed "-abcd" to your program and it handled "-a", "-b", and "-c", then $unparsed would be an array that only contains "-d".

More Reading
------------

[](#more-reading)

You can read the documentation for the individual classes to understand more about what they do and how they work.

- [OptionParameter](option-parameter.md)
- [OptionParser](option-parser.md)

Reference implementations are available in the [examples](examples/) directory in the repository.

Development
-----------

[](#development)

I would happily accept patches and suggestions.

Tests are *always* included. To get them running on your system, just make sure the submodules are checked out for the repository. If you don't have a `test/` folder then run this command:

```
git submodule update --init

```

From there you can run the tests. Start in the root of this repository and run this command.

```
test/run-tests

```

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

4254d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/30a66d371c597ec7b9bca1acb64fb0aa65c4b5729ee5164c15ab9877e32f08e3?d=identicon)[fidian](/maintainers/fidian)

---

Top Contributors

[![fidian](https://avatars.githubusercontent.com/u/428348?v=4)](https://github.com/fidian "fidian (6 commits)")

---

Tags

command-lineparserflagsoptioncommandflaggetoptline

### Embed Badge

![Health badge](/badges/tests-always-included-option-parser/health.svg)

```
[![Health](https://phpackages.com/badges/tests-always-included-option-parser/health.svg)](https://phpackages.com/packages/tests-always-included-option-parser)
```

###  Alternatives

[phalcon/cli-options-parser

Command line arguments/options parser.

181.0M7](/packages/phalcon-cli-options-parser)[nategood/commando

PHP CLI Commando Style

8123.3M38](/packages/nategood-commando)[aura/cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

1051.6M29](/packages/aura-cli)[deweller/cliopts

A no-nonsense command-line options parser and help generator for PHP CLI apps.

1518.3k](/packages/deweller-cliopts)[mrrio/shellwrap

Use any command-line tool as a PHP function.

738198.8k2](/packages/mrrio-shellwrap)[clue/commander

Finally a sane way to register available commands and arguments and match your command line in PHP.

16724.0k9](/packages/clue-commander)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
