PHP不区分NULL值(空值)和0值(数值)


PHP does not distinguish between NULL value (empty value) and 0 value (numerical)

我有一个PHP条件负责设置$hideZeroValues为FALSE,如果一个名为ro_capacity的字段是NULL(如果值返回为空的查询)。

if ($result_ro['ro_capacity'] == "") {
    $hideZeroValues="true";
}  
else{
    $hideZeroValues="false";
}

$result_ro['ro_capacity']结果的值存储在父DIV上作为data-capacity的值,$hideZeroValues条件结果的TRUE或FALSE存储在子行的data-zeroValues上。

因此,如果此条件正常工作,则无法同时拥有data-capacity=0data-zerovalues="true",因为0是一个值,而不是空值,而不是NULL。但是,正如您在这两个div中看到的那样,它发生了:第一个是OK (data-capacity=""data-zeroValues="true"),但在第二个中,即使查询返回值(0),它也保持设置为TRUE。

<div id="92" class="tableRow" title="Aula prueba" data-id="92" data-capacity="">
<span class="tableContentText centerText" data-zerovalues="true">-</span>
</div>
<div id="91" class="tableRow" title="Aula prueba" data-id="91" data-capacity="0">
<span class="tableContentText centerText" data-zerovalues="true">-</span>
</div>

第三个,值为12,工作正常(问题只发生在0和NULL,不与任何其他数值:

<div id="93" class="tableRow" title="Aula prueba" data-id="91" data-capacity="12">
<span class="tableContentText centerText" data-zerovalues="false">-</span>
</div>

我也试过了:

if ($result_ro['ro_capacity'] === "") { $hideZeroValues="true"; }  

if (is_null($result_ro['ro_capacity']) {    $hideZeroValues="true"; } 

这是因为0在PHP中被求值为false。

试试这个方法:

if(empty($result_ro['ro_capacity']) && $result_ro['ro_capacity'] !== 0)