PHP 比较 0 不起作用

PHP Comparing 0 does not work

我正在尝试根据逗号分隔值字符串中的小时字段将复选框设置为在 php 中选中。它适用于 1-23,但由于某种原因,小时 0 始终显示为已选中:

<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
    if(count($myhours) > 0) {
        for($h = 0; $h <= count($myhours); $h++) {
            if((int)$hour == (int)$myhours[$h]) {
                $checked = " checked ";
                break;
            }
        }
    } else {
        $checked = "";  
    }
    if(strlen($hour) == 1) {
        echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";   
    } else {
        echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
    }
    $checked = "";
}
?>

不完全是答案,但您的代码可以简化为:

$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
    echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';   
}

这里不需要第二个循环和更多变量。还要注意不要在没有任何检查的情况下直接从 $_REQUEST 输出值。

演示

Try before buy

问题已解决。实际上是 count($myhours) 导致了问题。基本上即使是空字符串,它仍然是 returns 一个包含 1 个元素的数组。更改为检查 count($myhours) > 1 是否一切正常:

<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
    if(count($myhours) > 1) {
        for($h = 0; $h <= count($myhours); $h++) {
            if((int)$hour == (int)$myhours[$h]) {
                $checked = " checked ";
                break;
            }
        }
    } else {
        $checked = "";  
    }
    if(strlen($hour) == 1) {
        echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";   
    } else {
        echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
    }
    $checked = "";
}
?>

问题很简单;查看外循环:

for ($hour = 0; $hour <= 23; $hour++) {

只考虑第一次迭代,所以$hourint(0)。进一步在代码中:

if(count($myhours) > 0) {
    for($h = 0; $h <= count($myhours); $h++) {

密切注意循环条件:

$h <= count($myhours)

考虑该循环的最后一次迭代,因此 $h 等于数组的大小。

if ((int)$hour == (int)$myhours[$h]) {

此时 $myhours[$h] 未定义,因为数组索引超出范围(并且会发出通知),因此 (int)$myhours[$h] 变为 (int)nullint(0).因此,当 $hour 的值为 int(0).

时,比较始终为真

解决方法是将循环条件改为:

$h < count($myhours)