PHP比较0不起作用

时间:2015-05-12 14:09:21

标签: php loops comparison

我正在尝试根据逗号分隔值字符串中的小时字段在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 = "";
}
?>

3 个答案:

答案 0 :(得分:2)

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

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)null int(0) 。因此,当$hour的值为int(0)时,比较始终为真。

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

$h < count($myhours)

答案 1 :(得分:1)

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

$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

答案 2 :(得分:0)

问题解决了。实际上导致问题的是count($myhours)。基本上即使使用空字符串,它仍然返回一个包含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 = "";
}
?>