PHP 使用 OR 运算符根据多个值检查值 [英] PHP check value against multiple values with OR-operator

查看:25
本文介绍了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?

推荐答案

逻辑||(OR) 运算符 无法正常工作.|| 运算符的计算结果始终为布尔值 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 语句:

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()

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

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))

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

您也可以使用 switch 来根据多个值检查您的值,然后让案例失败.

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 运算符根据多个值检查值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆