在 Echo 语句中使用三元运算符
Using Ternary Operator In Echo Statement
我正在尝试使用三元运算符,但结果不正确。我已经按照手册进行操作,但不知道发生了什么。控制台输出乱七八糟
php
echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':"").'>';
控制台输出
<div class="item><div class=" m_page="" outer-div"="">
<div class="inner-div" style=""><div class="momo_p">
echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':'"').'>';
也许吧?
检查你的报价。
echo '<div class="item'.(($month_number==='10' && $month_year==='2017') ? "active" : "").'">
在三元运算符后关闭 class 属性的双引号:
echo '<div class="item' . (($month_number==='09' && $month_year==='2017') ? ' active' : '') . '">';
使用以下代码:
PHP
$active = ($month_number==='09' && $month_year==='2017') ? 'active': '';
echo '<div class="item '.$active.'">';
这里是对单行代码的修改,添加了两个变量来测试代码,以便真实结果将 "active" 连接到 "item"。错误的结果导致 "item" 与空字符串连接,如下所示:
<?php
$month_number = "08";
$month_year = "2016";
echo "<div class=\"item";
// making the ternary expression more manageable
$month_result = ($month_number === "09");
$year_result = ($month_year === "2017");
echo ($month_result && $year_result)? "active":"";
echo "\"></div>";
直播代码here
注意:如果你想做一个回显语句,你可以编码如下:
$str = ($month_result && $year_result)? "active":"";
echo "<div class=\"item" . $str . "\"></div>";
查看实时代码 here
虽然您可以对属性使用双引号,对其他所有内容使用单引号,但更容易看到属性的转义双引号,即 \" 和外部字符串的双引号。
我正在尝试使用三元运算符,但结果不正确。我已经按照手册进行操作,但不知道发生了什么。控制台输出乱七八糟
php
echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':"").'>';
控制台输出
<div class="item><div class=" m_page="" outer-div"="">
<div class="inner-div" style=""><div class="momo_p">
echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':'"').'>';
也许吧?
检查你的报价。
echo '<div class="item'.(($month_number==='10' && $month_year==='2017') ? "active" : "").'">
在三元运算符后关闭 class 属性的双引号:
echo '<div class="item' . (($month_number==='09' && $month_year==='2017') ? ' active' : '') . '">';
使用以下代码:
PHP
$active = ($month_number==='09' && $month_year==='2017') ? 'active': '';
echo '<div class="item '.$active.'">';
这里是对单行代码的修改,添加了两个变量来测试代码,以便真实结果将 "active" 连接到 "item"。错误的结果导致 "item" 与空字符串连接,如下所示:
<?php
$month_number = "08";
$month_year = "2016";
echo "<div class=\"item";
// making the ternary expression more manageable
$month_result = ($month_number === "09");
$year_result = ($month_year === "2017");
echo ($month_result && $year_result)? "active":"";
echo "\"></div>";
直播代码here
注意:如果你想做一个回显语句,你可以编码如下:
$str = ($month_result && $year_result)? "active":"";
echo "<div class=\"item" . $str . "\"></div>";
查看实时代码 here
虽然您可以对属性使用双引号,对其他所有内容使用单引号,但更容易看到属性的转义双引号,即 \" 和外部字符串的双引号。