You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PHP字符串中使用三元运算符出现语法错误该如何修正?

错误原因
  • PHP 双引号字符串仅支持解析简单变量、对象属性、一维数组元素这类简单结构,无法直接执行三元运算这类逻辑表达式。将三元语法直接写在双引号包裹的字符串中时,PHP不会将其识别为可执行代码,只会当作普通文本处理,同时和HTML标签的单引号混排后会直接破坏PHP的语法结构,最终触发解析错误。
正确实现方案

你可以通过字符串拼接的方式拆分逻辑和静态字符串,PHP会先执行三元运算得到结果,再和前后的HTML字符串拼接,代码如下:

"hard_copy" => "<input type='checkbox' " . (($station->hard_copy == 1) ? 'checked' : '') . " name='station[]' id='hard-copy-$key' class='hard-copy' value='hardcopy-$station->id-1' >
<label for='hard-copy-$key' style='margin-left: 30%;'></label>",

如果字符串逻辑复杂,也可以用sprintf格式化输出,可读性更高:

"hard_copy" => sprintf(
    "<input type='checkbox' %s name='station[]' id='hard-copy-%s' class='hard-copy' value='hardcopy-%d-1' >
    <label for='hard-copy-%s' style='margin-left: 30%;'></label>",
    $station->hard_copy == 1 ? 'checked' : '',
    $key,
    $station->id,
    $key
),

内容的提问来源于stack exchange,提问作者saad nasim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:48:01