a more simple way to code in php "if ( $x == $a[1] || $x == $a[2] || $x == $a[3] ....)
As the title states, whats a more simple way to do
if ( $somevariable == $somearray[1] || $somevariable == $somearray[3] || $somevariable == $somearray[开发者_如何转开发10] )
Seems like even with 3 variables.. there would be a shortcut.
I know this doesnt work, but something like would be nice:
if ($somevariable == $somearray[1],$somearray[3],$somearray[10]) {
One option
if ( in_array( $somevariable, array( $somearray[1], $somearray[3], $somearray[10] ) ) {}
You could use in_array.
In fact, your code is already all right.
If you don't want to dive into depths of refactoring, just leave it as is. Because:
- it does exactly what it's intended for - checks some variable against some conditions.
- more important: it looks like the code to check some variable against some conditions. So, you could always tell what does it do. That's way more important than some fancy shortland.
In pursue for conciseness, you should not forget readability.
The only solution acceptable is one which no less readable than your current one. Which reads (literally: if you read it aloud) like it's intentded.
Example: by making such a function,
function whateverCondition($variable,$array) {
return ( $variable == $array[1]
|| $variable == $array[3]
|| $variable == $array[10]);
}
you can call it later this way,
if (whateverCondition($somevariable,$somearray))
keeping both conciseness and readability (if you name it properly).
As it was mentioned in comments, parameters seems a bit redundant. it depends. if it's going to be a function, keep them in place.
if this function going to be a method of some appropriate class - you can omit them, making it
if ($user->meetCondition())
Another option using array_intersect_key()
:
if (in_array($var, array_intersect_key($somearray, array_flip(array(1, 3, 10)))))
{
}
This is mostly useful if you have a large numbers of indexes to check.
In a variadic function, as @knittl suggested:
function in_array_keys($needle, $haystack)
{
$keys = array_flip(array_slice(func_get_args(), 2);
return in_array($needle, array_intersect_key($haystack, $keys)));
}
var_dump(in_array_keys($var, $somearray, 1, 2, 3));
精彩评论