tags:

views:

68

answers:

3

I am trying to find easier and simple way to code a logic.

That is if one variable is equal to any key values in an array.

For instance:

$someArray = array("a","b","c");
If($_GET["foobar"] == $someArray) {
     return true;
} else {
     return false;
}

If the $_GET["foobar"] had a value of A, B, or C, the case would return true. If it was any other values, it would return false.

Thanks for the help.

+2  A: 

You can use the in_array() function. I'm pretty sure it's exactly what you are looking for. Here is the function in the code sample you provided.

$someArray = array("a","b","c");
if(in_array($_GET["foobar"],$someArray)) {
     return true;
} else {
     return false;
}
Sam152
if capital `If` legal? Looks weird. And you should just return `in_array(...)` as that evaluates to a boolean anyway.
Mark
It's not my code, maybe the OP intends to add more instructions within the curly brackets.
Sam152
It's my typo. Sorry if I add any confusion.
Anraiki
+5  A: 
return in_array($_GET["foobar"], $someArray, true);

EDIT: Added optional true parameter.

Tom Bartel
I would further set the third - optional - parameter to `true` (in case you decide to add empty strings or 0 to `$someArray`). See the comments on the functions documentation page: http://php.net/manual/en/function.in-array.php
soulmerge
Good point soulmerge, I followed your advice.
Tom Bartel
+3  A: 

Rather than integer-indexed arrays, you can make use of associative arrays:

$someArray = array('a' => 1, 'b' => 1, 'c' => 1);
if (isset($someArray[$_GET['foobar']])) {
    ...
}

If you don't like to type out all the array values or the values of $someArray need to stay as they are, you can use array_flip:

$someArray = array('a', 'b', 'c');
...
$otherArray = array_flip($someArray);
if (isset($otherArray[$_GET['foobar']])) {
    ...
}

You can even store useful information in the values of the associative array.

outis