I’m writing a php code which is meant to run from the Unix console, with a couple of optional switches. I’m having problems making the script recognise the switches.
I run the script from the console this way
./<scriptname>.php v
Hoping that the ‘v’ switch will be picked up in the code, however it doesn’t appear to be. This is code that’s meant to pick it up.
global $argv; // specified, but probably not needed
$verbose = array_key_exists("v", $argv); // should work but it doesn't!
// $verbose= isset($_GET["v"]); // tried, but doesn't work because it's run from console
But in spite of the line var_dump($argv); outputting:
array(2) {
[0]=>
string(21) "./<scriptname>.php"
[1]=>
string(1) "v"
}
The following line echo "\nverbose: :$verbose:\n"; outputs verbose: :: (which is false ).
Why ?
Many thanks!
"v"is a value inside$argv, not a key. You can check for it within_array:Note:
in_arrayperforms a linear search of the array contents, which might not be the best way to go if one or more of the following conditions are true:falseNone of these is true in this scenario, so you are good here. But if the situation were different, you could consider using the values of the array as keys on another array so that you can check with an amortized cost of
O(1)instead ofO(n):