我有一行代码如下:
echo "Slope intercept form: $$"."y = ".toFraction($slope)."x + $b"."$$";
但是,我想添加一个if语句来检查数字是否为小数,以运行函数“toFraction”。如果它不是一个分数,我希望它只是在没有函数的情况下回显$ slope变量。换句话说,就像这样:
echo "Slope intercept form: $$"."y = ".if(strpos($number,".") !== false){toFraction($slope)}else{$slope}."x + $b"."$$";
但是,我不确定这是否可能,或者是否是,实现它的正确方法是什么?
答案 0 :(得分:1)
语法错误,如果使用?
和:
,则可以使用内联:
echo "Slope intercept form: $$"."y = ".(strpos($number,".") !== false ? toFraction($slope) : $slope) . "x + $b"."$$";
或尝试这种语法:
echo "Slope intercept form: $$"."y = ";
if(strpos($number,".") !== false) {
echo toFraction($slope)
} else {
echo $slope;
}
echo "x + $b"."$$";
内联ifs的语法模式如下所示:(
条件 ?
true path :
false path )
答案 1 :(得分:0)
echo "Slope intercept form: $$"."y = ".((strpos($number,".") !== false) ? toFraction($slope): $slope)."x + $b"."$$";
答案 2 :(得分:0)
echo "Slope intercept form: $$"."y = " . ((strpos($number,".") !== false ? toFraction($slope) : $slope) . "x + $b" . "$$");
答案 3 :(得分:0)
echo "Slope intercept form: $$"."y = ";
if(strpos($number,".") !== false) echo toFraction($slope); else echo $slope;
echo "x + $b"."$$";
答案 4 :(得分:0)
请记住两条简单的规则:
所以
if (strpos($number,".") !== false) {
$slope = toFraction($slope);
}
echo 'Slope intercept form: $$y = '.$slope.'x + '.$b.'$$';