dps69208 2013-11-13 09:23
浏览 226
已采纳

检查变量是否不等于多个字符串值的更简单方法?

Current Codes:

<?php

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

    // Do something

  }

?>

And:

<?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.

  • 写回答

5条回答 默认 最新

  • dtotuki47568 2013-11-13 09:59
    关注

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

    or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

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

    is the same as:

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

    ... 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

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

    if (true) {
    

    equals

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog