简体   繁体   English

在Echo语句中使用三元运算符

[英]Using Ternary Operator In Echo Statement

I'm trying to use a ternary operator but the outcome is not right. 我正在尝试使用三元运算符,但结果不正确。 I've followed the manual but have no idea what's going on. 我遵循了手册,但不知道发生了什么。 The outpout in the console is messy. 控制台中的输出混乱。

php PHP

echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':"").'>';

console output 控制台输出

<div class="item><div class=" m_page="" outer-div"="">
<div class="inner-div" style=""><div class="momo_p"> 

三元运算符后,将class属性的双引号引起来:

echo '<div class="item' . (($month_number==='09' && $month_year==='2017') ? ' active' : '') . '">';
echo '<div class="item'.(($month_number==='09' && $month_year==='2017')?' active"':'"').'>';

也许?

检查您的报价。

echo '<div class="item'.(($month_number==='10' && $month_year==='2017') ? "active" : "").'">

Use below code: 使用以下代码:

PHP PHP

$active = ($month_number==='09' && $month_year==='2017') ? 'active': '';
echo '<div class="item '.$active.'">';

Here is a reworking of the one liner with the addition of two variables to test the code such that a true result concatenates "active" to "item". 这是一个底线的重做,其中添加了两个变量以测试代码,以使真实结果将“活动”连接为“项目”。 A false result leads to "item" being concatenated with an empty string, as follows: 错误的结果导致“ 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>";

Live code here 现场代码在这里

Note: if you wish to do one echo statement you could code as follows: 注意:如果您希望执行一个echo语句,则可以编写如下代码:

$str =  ($month_result && $year_result)? "active":"";
echo "<div class=\"item" . $str  . "\"></div>";

See live code here 在此处查看实时代码

While you could use double quotes for attributes and single quotes for everything else, it is easier to see escaped double quotes for attributes, ie \\" and double quotes for the outer strings. 虽然您可以对属性使用双引号,对其他所有属性使用单引号,但更容易看到转义的属性双引号,即\\“和外部字符串的双引号。

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

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