PHP 8.5.0 Alpha 4 available for testing

Voting

: min(zero, zero)?
(Example: nine)

The Note You're Voting On

mbirth at webwriters dot de
17 years ago
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser.

<?php
/**
* Parses $GLOBALS['argv'] for parameters and assigns them to an array.
*
* Supports:
* -e
* -e <value>
* --long-param
* --long-param=<value>
* --long-param <value>
* <value>
*
* @param array $noopt List of parameters without values
*/
function parseParameters($noopt = array()) {
$result = array();
$params = $GLOBALS['argv'];
// could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly
reset($params);
while (list(
$tmp, $p) = each($params)) {
if (
$p{0} == '-') {
$pname = substr($p, 1);
$value = true;
if (
$pname{0} == '-') {
// long-opt (--<param>)
$pname = substr($pname, 1);
if (
strpos($p, '=') !== false) {
// value specified inline (--<param>=<value>)
list($pname, $value) = explode('=', substr($p, 2), 2);
}
}
// check if next parameter is a descriptor or a value
$nextparm = current($params);
if (!
in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
$result[$pname] = $value;
} else {
// param doesn't belong to any option
$result[] = $p;
}
}
return
$result;
}
?>

A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst

and an in-program call parseParameters(array('f')); would yield in a resulting array:

Array
(
[0] => alfons
[a] => 1
[b2] => 1
[c] => 1
[d] => 2
[e] => 3=4
[f] => 1
[1] => alber t
[2] => hans
[3] => wurst
)

As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true".

<< Back to user notes page

To Top