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

时间:2016-05-01 20:53:22

标签: php if-statement comparison

我有一个文件名($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 = '';
}

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

3 个答案:

答案 0 :(得分:10)

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;

}

答案 1 :(得分:1)

我只想将其更改为:

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

答案 2 :(得分:0)

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

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