views:

144

answers:

4

How would I go about converting this if statement:

for($i = 1; $i < $argc; $i++)
{
    ...
    if(in_array($argv[$i], array('-V', '--version')))
    {
        $displayVersion = TRUE;
    }
    ...
}

Into a switch case without needing to write two switch statements?

+12  A: 
switch($argv[$i])
{
    case '-V':
    case '--version':
        $displayVersion = true;
    break;
}
Tim Cooper
I didn't even think about doing this way! Thank you so much!
Urda
+2  A: 
switch ($argv[$i])
{
    case '-V':
    case '--version':
        $displayVersion = true;
        break;
    case 'other':
        // do other stuff
        break;
    default:
        // your "else" case would go here
        break:
}
Mike
+4  A: 

A direct translation would be as follows:

switch(in_array($argv[$i], array('-V', '--version'))){
    case true:
        $displayVersion = TRUE; break;
}

However you could also do something like this, which is clearer.

switch($argv[$i]){
    case '-V':
    case '--version':
        $displayVersion = TRUE; break;
}

Depending on what you want to do, a one liner may be more clear, although it differs from the above code in that the variable will be set to false if in_array($argv[$i], array('-V', '--version')) is false. Given your variable name I doubt this is a bad thing.

$displayVersion = in_array($argv[$i], array('-V', '--version'));
Yacoby
+2  A: 

In addition to fixing this, you may want to look at the PHP getopt command, which is a function to process command-line arguments in both short and long formats.

Edit: Actually, here's a code block

$options = getopt('V', array('version'));

if ($options['V'] || $options['version']) {
    $displayVersion = TRUE;
}

Note that you need PHP 5.3 for this to work on Windows.

R. Bemrose