2016-05-01 57 views
3

私はファイル名($fname)を持っていて、後で " - "を付けてファイルタイプに$pClassを割り当てる必要があります。現在、私はいつもtext-というファイルタイプを持っています。OR演算子で複数の値に対するPHPのチェック値

//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文はなぜ機能しないのですか?

+0

のどのような値をチェックして最初のデバッグ$ extが – Chaim

+0

に設定されています再チェックしたところ$ extが各ファイルに対して正しく設定されています(example.phpは "php"を返します) – mcky

+0

(( 'txt')||( 'rtf')||( 'log') ||( 'docx'))は、 aysは1に評価されてから$ extと比較されます – Chaim

答えて

7

logical ||(OR) operatorは動作しません。 ||演算子は、常にTRUEまたはFALSEのブール値に評価されます。したがって、あなたの例では、文字列はブール値に変換され、比較されます。

文の場合:別の方法を使用することができます。この問題を解決し、あなたはあなたにそれを望むようなコードが動作するように取得するには

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

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

はにダウンしています。問題を解決し、複数の値に対して、自分の価値観をチェックする

多重比較

一つの方法は、実際には複数の値に対して値を比較すること、である:

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

in_array()

もう一つの方法はにありますin_array()関数を使用し、値が配列値のいずれかと等しいかどうかを確認してください:

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

注:2番目のパラメータは、厳密な比較のためにある

switch()

また、複数の値と照らし合わせて値をチェックし、念のフォールスルーできるようにswitchを使用することができます。

switch($ext){ 

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

} 
+0

私たちはこれについて良い複製を持っていると教えてください:)それ以外の場合は、今すぐここで作成してください。 – Rizier123

+0

ありがとう、私は今これを試しに行くよ – mcky

+0

http:// stackoverflow。com/questions/4106382/compare-multiple-values-in-php – Chaim

0

あなたは、複数の文字列に値を比較することin_array()を使用することができます。

if(in_array($ext, array('txt','rtf','log','docx')){ 
    // Value is found. 
} 
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 = ''; 
}