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语句不起作用?

逻辑||(OR)运算符不能按预期工作。||运算符的计算结果始终为布尔值TRUE或FALSE。因此,在您的示例中,字符串被转换为布尔值,然后进行比较。

If语句:

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

我只需将其更改为以下内容:

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

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

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