首页 > 解决方案 > PHP populated field returns 0 even if populated

问题描述

I have a MySQL row I get data from by doing this:

...['immobile' => $dati_immobile->row(),]...

I then have a table and I pass every field inside a function, this is the function code:

public function brochurefield($field, $label, $checkbox = false)
{
    if($field == 0){
        return '<tr><td>'.$label.' Is zero</td></tr>';
    }
}

When I echo this function with a text field taken from the MySQL it returns 0:

//This returns "Accessori Bagno Is zero"
<?= $this->ui_model->brochurefield($immobile->arredo_bagno, "Accessori Bagno") ?>

//This returns "termo arredo" (text from DB)
<tr><td><?= $immobile->arredo_bagno ?></td></tr>

It basically reads the field to be 0 instead of "termo arredo". While if I check the field on $field == "0" (string) and $field == '' (empty string) the result is false.

The result is true only when I check it against a 0 (int) value.

The problem happens only on string values, while on int values I get the expected results (brochurefield(32,"test") returns correctly the number 32).

I use PHP 7.1.1

标签: php

解决方案


你必须使用你的 if 条件。

该值由字符串的初始部分给出。如果字符串以有效的数字数据开头,这将是使用的值。否则,该值将为 0(零)。有效的数字数据是一个可选的符号,后跟一个或多个数字(可选地包含一个小数点),后跟一个可选的指数。指数是“e”或“E”后跟一位或多位数字。

这意味着:

("test" == 0) === true
("1test" == 0) === false


if ($field == "" || $field == "0" || (is_numeric($field) && $field == 0)) {

如需更多参考,您可以访问PHP 手册


推荐阅读