三項演算子を使用するこの操作を実行するように求められました。
$test='one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
これは2つを出力します(phpを使用して確認)。
これのロジックについてはまだよくわかりません。どなたかこの論理を教えてください。
三項演算子を使用するこの操作を実行するように求められました。
$test='one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
これは2つを出力します(phpを使用して確認)。
これのロジックについてはまだよくわかりません。どなたかこの論理を教えてください。
さて、?と : 優先順位が同じであるため、PHP は左から右に解析し、各ビットを順番に評価します。
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
First$test == 'one'
は true を返すため、最初のかっこの値は「1」です。2 番目の 3 項は次のように評価されます。
'one' /*returned by first ternary*/ ? 'two' : 'three'
'one' は true (空でない文字列) であるため、'two' が最終結果です。
基本的に、インタープリターはこの式を左から右に評価するため、次のようになります。
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
と解釈されます
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
また、'one' と 'two' の両方が null/o/other 形式の false ではないため、括弧内の式は true と評価されます。したがって、次のようになるとします。
echo $test == 'one' ? FALSE : $test == 'two' ? 'two' : 'three';
3つ印刷されます。正常に機能させるには、三項演算子の組み合わせを忘れて、より複雑なロジックに通常の ifs/switch を使用するか、少なくとも括弧を使用してインタープリターがロジックを理解できるようにし、標準の LTR 方法でチェックを実行しないようにする必要があります。
echo $test == 'one' ? 'one' : ($test == 'two' ? 'two' : ($test == 'three' ? 'three' : 'four'));
//etc... It's not the most understandable code...
//You better use:
if($test == 'one')
echo 'one';
else { //or elseif()
...
}
//Or:
switch($test) {
case 'one':
echo 'one';
break;
case 'two':
echo 'two';
break;
//and so on...
}
括弧を使用すると正しく機能します。
<?
$test='one';
echo $test == 'one' ? 'one' : ($test == 'two' ? 'two' : 'three');
私はそれを100%理解していませんが、括弧なしでは、通訳者にとって、ステートメントは次のように見える必要があります:
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
最初の条件の結果は、三項演算全体の結果として返されるようです。
三項演算子は出現順に実行されるため、実際には次のようになります。
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
PHPのドキュメントには次のように書かれています:
注:三項式を「積み重ねる」ことは避けることをお勧めします。単一のステートメント内で複数の三項演算子を使用した場合の PHP の動作は、自明ではありません。
Example #3 自明でない三項の振る舞い
<?php // on first glance, the following appears to output 'true' echo (true?'true':false?'t':'f'); // however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right // the following is a more obvious version of the same code as above echo ((true ? 'true' : false) ? 't' : 'f'); // here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>
false ステートメントを括弧で囲むと、次のように出力されますone
。
echo $test == 'one' ? 'one' : ($test == 'two' ? 'two' : 'three');
次のように評価されると思います。
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
($test == 'one' ? 'one' : $test == 'two') は非ゼロ/null であるため、'two' は論理出力です。
正しく動作させたい場合は、次のように記述します。
echo $test == 'one' ? 'one' : ($test == 'two' ? 'two' : 'three');
ネストされた 3 項演算はひどいものです。上記の説明は、その理由を示しています。
基本的にこれはロジックです:
is $test == 'one'
if TRUE then echo 'one'
else is $test == 'two'
if TRUE then echo 'two'
else echo three