检查变量是否不等于多个字符串值的更简单方法? [英] Simpler way to check if variable is not equal to multiple string values?

查看:727
本文介绍了检查变量是否不等于多个字符串值的更简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前代码:

<?php

  // See the AND operator; How do I simplify/shorten this line?
  if( $some_variable !== 'uk' && $some_variable !== 'in' ) {

    // Do something

  }

?>

并且:

<?php

  // See the OR operator; How do I simplify/shorten this line?
  if( $some_variable !== 'uk' || $some_variable !== 'in' ) {

    // Do something else

  }

?>

是否有更简单(即更短)的方式来编写这两个条件?

Is there a simpler (i.e. shorter) way to write the two conditions?

注意:是的,它们是不同的,我期待缩短代码的不同方法。

NOTE: Yes, they are different, and I am expecting different ways to shorten the codes.

推荐答案

对于您的第一个代码,您可以使用
给出的答案的简短更改@ShankarDamodaran
使用 in_array()

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

与以下内容相同:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

......但更短。特别是如果你比较'uk'和'in'更多。
我不使用额外的变量( Shankar使用$ os ),而是在if语句中定义数组。有些人可能会发现它很脏,我发现它很快又整洁:D

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

第二个代码的问题在于它可以很容易地用TRUE进行交换,因为:

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

等于

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

你问的是字符串的值是不是A还是不是B.如果是A,它绝对不是B,如果它是B,它肯定不是A.如果它是C或字面上的任何其他东西,它也不是A而不是B.所以该陈述总是(没有考虑到schrödingers法律)返回true。

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

这篇关于检查变量是否不等于多个字符串值的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆