在 PHP 中,可以进行条件变量替换吗?

发布于 2024-10-10 08:49:21 字数 1260 浏览 6 评论 0原文

我想知道 PHP 中是否可以执行以下操作:

<?php echo "Hello {isset($name) ? $name : 'World'}!\n"; ?>

或者我必须执行以下操作吗?

<?php echo "Hello " . ( isset($name) ? $name : 'World' ) . "!\n"; ?>

一般来说,我更喜欢替换而不是串联,因为我发现字符串串联会使字符串过长而难以阅读。

其上下文是我正在根据数据库查询来决定默认情况下应选择选择标记中的哪个选项。

完整的上下文:

<?php   
echo "
<form action='add_demographics.php' method='post'>
   <table>
      <input type=hidden name=userId value='{$_SESSION['username']}'/>
      <tr><td>User ID:</td><td>{$_SESSION['username']}</td></tr>";

foreach ($inputLabels as $i => $value)
{
    echo "
      <tr>
         <td>{$value['text']}</td>
         <td><select name=$i>";

    foreach ($value["options"] as $optionName => $optionValue)
    {
    echo "
            <option value=$optionValue {($result[$i]==$optionValue ? ' selected=true' : '')}>$optionValue</option>";
    }
    echo "
          </select></td>
      </tr>";
}

echo "
      <tr><td><input type='submit' name='submit' value='Submit' /></td></tr>
   </table>
</form>";
?>

I was wondering if something like the following would be possible in PHP:

<?php echo "Hello {isset($name) ? $name : 'World'}!\n"; ?>

or do I have to do the following?

<?php echo "Hello " . ( isset($name) ? $name : 'World' ) . "!\n"; ?>

In general I prefer substitution over concatenation as I find that string concatenation can make strings harder to read by making them overly long.

The context of which is that I'm deciding which option in a select tag should be selected by default based on a database query.

The full context:

<?php   
echo "
<form action='add_demographics.php' method='post'>
   <table>
      <input type=hidden name=userId value='{$_SESSION['username']}'/>
      <tr><td>User ID:</td><td>{$_SESSION['username']}</td></tr>";

foreach ($inputLabels as $i => $value)
{
    echo "
      <tr>
         <td>{$value['text']}</td>
         <td><select name=$i>";

    foreach ($value["options"] as $optionName => $optionValue)
    {
    echo "
            <option value=$optionValue {($result[$i]==$optionValue ? ' selected=true' : '')}>$optionValue</option>";
    }
    echo "
          </select></td>
      </tr>";
}

echo "
      <tr><td><input type='submit' name='submit' value='Submit' /></td></tr>
   </table>
</form>";
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你的心境我的脸 2024-10-17 08:49:21

不,不能那样做。您需要在字符串之外执行此操作并连接。 php 在字符串中唯一要做的就是查找并计算单个 $var (无表达式) - 如果您使用双引号或等效的heredoc(php 不会计算单引号中的变量)

nope, cannot do that. You need to do it outside of the string and concat. The only thing php will do inside a string is look for and evaluate a single $var (no expressions) - if you use double quotes or equivalent heredoc (php does not evaluate vars in single quotes)

滿滿的愛 2024-10-17 08:49:21

不,不可能按照你要求的方式去做。

然而,解决您的特定问题的方法可能是在 foreach 循环的顶部分配一个变量来保存是否应选择该选项,然后回显该变量作为输出的一部分:

foreach ($value["options"] as $optionName => $optionValue)
{
    $selected = $result[$i] == $optionValue ? "selected='selected'" : "";
    echo "
        <option value=$optionValue $selected>$optionValue</option>";
}

No, it isn't possible to do it the way you're asking.

A solution to your specific problem, however, could be to assign a variable at the top of the foreach loop to hold whether or not that option should be selected, then echo that variable as part of your output:

foreach ($value["options"] as $optionName => $optionValue)
{
    $selected = $result[$i] == $optionValue ? "selected='selected'" : "";
    echo "
        <option value=$optionValue $selected>$optionValue</option>";
}
错爱 2024-10-17 08:49:21
<?
    function is($var,$sub){
      return isset($var)?$var:$sub;
    }

    echo 'Hello, '.is($name,'World').'!\r\n';

    $name = 'Bob';

    echo 'Hello, '.is($name,'World').'!\r\n';
?>

也许是因为人手不足呢?

<?
    function is($var,$sub){
      return isset($var)?$var:$sub;
    }

    echo 'Hello, '.is($name,'World').'!\r\n';

    $name = 'Bob';

    echo 'Hello, '.is($name,'World').'!\r\n';
?>

Maybe for short-handing it?

泅人 2024-10-17 08:49:21

你可以做这样的事情:

$default = "World";
$name = "Dunes";
echo "Hello {${isset($name) ? 'name' : 'default'}}";

来自 webbiedave 的更新:

“永远不要这样做,因为使用三元运算符来引用丢弃变量只是为了避免串联,这绝对是一种残暴的编码实践!

You could do something like this:

$default = "World";
$name = "Dunes";
echo "Hello {${isset($name) ? 'name' : 'default'}}";

UPDATE from webbiedave:

"Don't ever do this as it's absolutely atrocious coding practice to use the ternary operator to reference a throw away variable variable simply to avoid concatenation!

春庭雪 2024-10-17 08:49:21

鉴于你想做的事情。我想说

$string = isset($name) ? $name : 'World';
$result = "Hello $string!\n";
echo $result;

Given what you want to do. I'd say

$string = isset($name) ? $name : 'World';
$result = "Hello $string!\n";
echo $result;
情话已封尘 2024-10-17 08:49:21

实际上从来没有需要它。
学习使用模板。
HTML应该是HTML,而不是PHP中硬编码的一些抽象数据

<form action='add_demographics.php' method='post'>
   <table>
      <input type=hidden name=userId value='<?=_h($_SESSION['username'])?>'/>
      <tr><td>User ID:</td><td><?=_h($_SESSION['username'])?></td></tr>
<? foreach ($inputLabels as $i => $value): ?>
      <tr>
         <td><?=_h($value['text'])?></td>
         <td><select name="<?=$i?>">
<?   foreach ($value["options"] as $optionName => $optionValue): ?>
            <option value="<?=$optionValue?>" <? if ($result[$i]==$optionValue): ?> selected=true<? endif ?>>
              <?=$optionValue?>
            </option>
<?   endforeach ?>
          </select></td>
      </tr>
<? endforeach ?>
      <tr><td><input type='submit' name='submit' value='Submit' /></td></tr>
   </table>
</form>

It is never actually required.
Learn to use templates.
HTML should be HTML, not some abstract data hardcoded in PHP

<form action='add_demographics.php' method='post'>
   <table>
      <input type=hidden name=userId value='<?=_h($_SESSION['username'])?>'/>
      <tr><td>User ID:</td><td><?=_h($_SESSION['username'])?></td></tr>
<? foreach ($inputLabels as $i => $value): ?>
      <tr>
         <td><?=_h($value['text'])?></td>
         <td><select name="<?=$i?>">
<?   foreach ($value["options"] as $optionName => $optionValue): ?>
            <option value="<?=$optionValue?>" <? if ($result[$i]==$optionValue): ?> selected=true<? endif ?>>
              <?=$optionValue?>
            </option>
<?   endforeach ?>
          </select></td>
      </tr>
<? endforeach ?>
      <tr><td><input type='submit' name='submit' value='Submit' /></td></tr>
   </table>
</form>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文