简体   繁体   English

一种更简单的在php中编码的方法“if($ x == $ a [1] || $ x == $ a [2] || $ x == $ a [3] ......)

[英]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. 看起来甚至有3个变量..会有一个捷径。

I know this doesnt work, but something like would be nice: 我知道这不起作用,但是类似的东西会很好:

if ($somevariable == $somearray[1],$somearray[3],$somearray[10]) {

一种选择

if ( in_array( $somevariable, array( $somearray[1], $somearray[3], $somearray[10] ) ) {}

你可以使用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() : 使用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: 在变量函数中,@ knittl建议:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM