【问题标题】:PHP check value against multiple values with OR-operatorPHP 使用 OR 运算符针对多个值检查值
【发布时间】:2016-05-01 20:53:21
【问题描述】:

我有一个文件名($fname),之后我需要用“-”将$pClass 分配给文件类型。目前我总是得到text-,不管它是什么文件类型。

//This gets the extention for the file and assigns the class to the icon <i>
$pieces = explode('.', $fname);
$ext = array_pop($pieces);

if($ext == (('txt')||('rtf')||('log')||('docx'))){
  $pClass = 'text-';
}
else if($ext == (('zip')||('sitx')||('7z')||('rar')||('gz'))){
  $pClass = 'archive-';
}
else if($ext == (('php')||('css')||('html')||('c')||('cs')||('java')||('js')||('xml')||('htm')||('asp'))){
  $pClass = 'code-';
}
else if($ext == (('png')||('bmp')||('dds')||('gif')||('jpg')||('psd')||('pspimage')||('tga')||('svg'))){
  $pClass = 'image-';
}
else {
  $pClass = '';
}

为什么我的带有 OR 运算符的 if 语句不起作用?

【问题讨论】:

  • 首先通过检查 $ext 的值被设置为什么来调试
  • 我刚刚重新检查并为每个文件正确设置了 $ext(example.php 返回“php”)
  • (('txt')||('rtf')||('log')||('docx')) 将始终评估为 1,然后才与 $ext
  • 您最初的 if 将始终返回 true,因此您总是返回 test-
  • 解决方案不属于问题。为此,我们有答案。

标签: php if-statement comparison


【解决方案1】:

logical ||(OR) operator 无法正常工作。 || 运算符的计算结果始终为 TRUE 或 FALSE 布尔值。因此,在您的示例中,您的字符串被转换为布尔值,然后进行比较。

如果语句:

if($ext == ('txt' || 'rtf'|| 'log' || 'docx'))

归结为:

if($ext == (TRUE || TRUE || TRUE || TRUE))
if($ext == TRUE)

要解决此问题并让代码按您的意愿工作,您可以使用不同的方法。

多重比较

解决问题并根据多个值检查值的一种方法是,将值与多个值进行实际比较:

if($ext == "txt" || $ext == "rtf" /* || ... */)

in_array()

另一种方法是使用函数in_array() 并检查值是否等于数组值之一:

if(in_array($ext, ["txt", "rtf" /* , ... */], TRUE))

注意:第二个参数用于严格比较

switch()

您也可以使用switch 来对照多个值检查您的值,然后让案例通过。

switch($ext){

    case "txt":
    case "rtf":
 /* case ...: */
        $pClass = "text-";
    break;

}

【讨论】:

  • 请告诉我我们有一个很好的副本:)?否则我们现在就在这里创建它。
  • 谢谢,我现在就去试试这个
  • 效果很好,感谢您帮助展示如何以正确的方式进行操作
【解决方案2】:

我只想把它改成这样:

//This gets the extention for the file and assigns the class to the icon <i>
$pieces = explode('.', $fname);
$ext = array_pop($pieces);
if(in_array($ext,array('txt','rtf','log','docx'))){
    $pClass = 'text-';
}elseif(in_array($ext,array('zip','sitx','7z','rar','gz'))){
    $pClass = 'archive-';
}elseif(in_array($ext,array('php','css','html','c','cs','java','js','xml','htm','asp'))) {
    $pClass = 'code-';
}elseif(in_array($ext,array('png','bmp','dds','gif','jpg','psd','pspimage','tga','svg'))){
    $pClass = 'image-';
}else {
    $pClass = '';
}

【讨论】:

    【解决方案3】:

    您可以使用in_array() 将一个值与多个字符串进行比较:

    if(in_array($ext, array('txt','rtf','log','docx')){
        // Value is found.
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 1970-01-01
      • 2012-07-19
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2021-07-06
      • 1970-01-01
      相关资源
      最近更新 更多