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

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

本文介绍了PHP使用OR运算符检查多个值的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a filename($fname) and I need to assign $pClass to the file type with a "-" afterwards. Currently I always get text-, no matter what file type it is.

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

Why doesn't my if statement with the OR operator works?

推荐答案

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

The logical ||(OR) operator doesn't work as you expect it to work. The || operator always evaluates to a boolean either TRUE or FALSE. So in your example your strings get converted into booleans and then compared.

如果声明:

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

归结为:

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






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


To solve this problem and get the code to work as you want it to you can use different methods.

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

One way to solve the problem and check your values against multiple values is, to actually compare the value against multiple values:

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





另一种方法是使用函数 in_array ()并检查值是否为eq ual到其中一个数组值:

in_array()

Another way is to use the function in_array() and check if the value is equal to one of the array values:

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

您还可以使用开关根据多个值检查您的价值,然后让案件落空。

You could also use switch to check your value against multiple values and just let the case fall through.

switch($ext){

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

}

这篇关于PHP使用OR运算符检查多个值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:58