PHP 使用 OR 运算符对照多个值检查值

PHP check value against multiple values with OR-operator

我有一个文件名($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 语句不起作用?

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;

}

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

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

我会简单地把它改成这样:

//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 = '';
}