简体   繁体   English

PHP如何将if语句放在echo块内

[英]PHP how to put an if statement inside an echo block

I have the following if statement: 我有以下if语句:

<?php if ( isset ( $prfx_stored_meta['wedding-user'] ) ) selected( $prfx_stored_meta['wedding-user'][0], 'select-one' ); ?>

which I need to insert into this echo statement: 我需要将其插入到此echo语句中:

$users = get_users();
$i = 0;
// Array of WP_User objects.
foreach ( $users as $user ) {
    echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
    $i++;
}

Just before closing the <option> tag 在关闭<option>标记之前
I'm not sure how to add an if statement inside of an echo 我不确定如何在回显中添加if语句

Don't. 别。

Ignoring for a moment that outputting your HTML embedded inside echo statements like this is an anti-pattern (consider using a templating engine!), you will make your code really hard to read by mixing your logic and your content even more, which you will be doing if you employ the conditional operator * here. 暂时忽略将您的HTML嵌入到echo语句中这样的输出是一种反模式(考虑使用模板引擎!),您将通过混合更多的逻辑和内容来使代码真正难以阅读,您将如果您在此处雇用条件运算符 *,则该操作

In fact, in general, if you have anything more than basic string interpolation in your output statements, you're not separating your logic and content enough. 实际上,通常,如果输出语句中除了基本的字符串插值以外,还没有足够的逻辑和内容。

Here, it will look something like this: 在这里,它看起来像这样:

$users = get_users();
$i = 0;
// Array of WP_User objects.
foreach ( $users as $user ) {
   echo "<option value='select-$i' ";
   if (isset($prfx_stored_meta['wedding-user']))
      echo selected($prfx_stored_meta['wedding-user'][0], 'select-one');
   echo ">" . esc_html( $user->display_name ) . "</option>";

   $i++;
}

See how messy it is? 看到它有多混乱吗? And with a long line using the conditional operator it would be even worse ! 如果使用条件运算符排长队,那就更糟了

* Not the "ternary operator"! *不是“三元运算符”! Being "ternary" is its arity, not its name. “三元”是它的友善,而不是它的名字。

You have to use ternary operator : www.php.net/ternary 您必须使用三元运算符:www.php.net/ternary

Try this : 尝试这个 :

echo "<option value='select-$i' >" . esc_html( $user->display_name ) . ((isset($prfx_stored_meta['wedding-user'])?selected( $prfx_stored_meta['wedding-user'][0], 'select-one'):'')."</option>";

Source : if block inside echo statement? 消息来源: 如果在echo语句内阻塞?

您将需要使用一个三元运算符,该运算符用作缩短的IF / Else语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM