2 つの変数が同じかどうかを確認し、同じ場合は文字列をエコーします。これは連結内で可能ですか? そして、別の関数を作成せずにそれを行うには?
例えば
$var = 'here is the first part and '. ( $foo == $bar ) ? "the optional middle part" .' and the rest of the string.'
編集
注、 .なしでそれを行う方法があるかどうかを調べてい: ''
ます。よろしければ「二項演算子」。
2 つの変数が同じかどうかを確認し、同じ場合は文字列をエコーします。これは連結内で可能ですか? そして、別の関数を作成せずにそれを行うには?
例えば
$var = 'here is the first part and '. ( $foo == $bar ) ? "the optional middle part" .' and the rest of the string.'
編集
注、 .なしでそれを行う方法があるかどうかを調べてい: ''
ます。よろしければ「二項演算子」。
物事をあまりにも短くしようとしないでください。: ''
物事が機能するためには、それが必要です。
(condition) ? "show when true" : ""
条件に応じて任意のテキストを表示するために使用します。三項演算子は 3 つの部分で構成されているため、そのように命名されています。
$var = 'here is the first part and '. (( $foo == $bar ) ? "the optional middle part" : "") .' and the rest of the string.';
三項演算子の構文は次のとおりです。
(any condition)?"return this when condition return true":"return this when condition return false"
したがって、文字列では次のようになります
$var = 'here is the first part and '.( ( $foo == $bar ) ? "the optional middle part":"") .' and the rest of the string.'
これは、条件に else past と operator precedence がないことを意味します
質問が「コロンと空の引用符なしで実行できますか?」答えはノーです。締めくくりが必要:''
であり、あなたの欲求を明確にするために括弧を使用するのが最善です.
$var = 'here is the first part and '.
(( $foo == $bar ) ? "the optional middle part":'') .
' and the rest of the string.'
ここでの最大の問題は、インラインで処理しようとしていることだと思います。これは基本的に同じプロセスに要約され、閉じられていない三項を使用しません。
$var = 'here is the first part and ';
if( $foo == $bar ) $var .= "the optional middle part";
$var .= ' and the rest of the string.';
これは、条件文が文字列を壊すことを心配する必要なく、同じ目標を達成する別の方法です。
$middle = '';
if( $foo == $bar ) $middle = ' the optional middle part and';
$var = sprintf('here is the first part and%s the rest of the string.',$middle);
さて、あなたが不必要に賢くなるつもりなら、代わりにこれを行うことができると思います:
$arr = array('here is the first part and',
'', // array filter will remove this part
'here is the end');
// TRUE evaluates to the key 1.
$arr[$foo == $bar] = 'here is the middle and';
$var = implode(' ', array_filter($arr));