我希望我的函数执行以下操作:
如果价格为 0
,则返回free
消息。
如果价格为正数,则显示价格。
如果 price 值不可用 - 例如:如果 price 的数据库单元格为 null,或者具有类似 unknown
的值,则返回unavailable
消息。
所以我来了这个代码:
function get_rate($foo,$bar) {
if ($bar== "something") {
//$test= "testing";
} elseif ($foo== 0) {
$message = 'Free';
} elseif ($foo> 0) {
$message = '$'.$foo;
} else {
$message = 'Unavailable';
}
return $message;
}
.HTML:
<?= get_rate( $price) ?>
但对于值:
$price="unknown";
或者如果$price
为空,我仍然收到"免费"消息。
现在您有两种解决方案:
解决方案 1:
else if ($foo === 0) // use === for checking value and datatype
解决方案 2:
else if ($foo == 0 && $foo != null) // adding != null
值""
或null
被视为 0,如果您还使用 ===
检查数据类型,此问题将解决,否则使用第二种解决方案。
在您发表评论后,分享一个基本示例,您将得到以下想法:
$foo = 'bla';
var_dump($foo);
它会给你string(3) "bla"