php表单复选框值获取错误

时间:2013-06-09 18:44:20

标签: php html

我找不到错误 每件事都可以预期复选框值不会像列表一样

<?php

if(isset($_POST['sub']))
{
    $fname = $_POST['fname'];
    $age = $_POST['age'];
    $comment = $_POST['comment'];
    $gender = $_POST['gender'];
    $hobby_temp = $_POST['hobby'];
    $size = count($hobby_temp);
    for($i = 0; $i < size; $i++)
    {
        $hobby=$hobby.','.$hobby_temp[$i];
    }
    echo 'Name:'.$fname.'<br>';
    echo 'age:'.$age.'<br>';
    echo 'comment:'.$comment.'<br>';
    echo 'gender:'.$gender.'<br>';
    echo 'Hobbies:'.$hobby.'<br>';
}
?>

注意:每件事都表现出爱好

3 个答案:

答案 0 :(得分:0)

您的问题在这里:

$hobby=$hobby.','.$hobby_temp[$i];

应该是

$hobby = "" //initialize outside the loop
for($i = 0; $i < $size; $i++){
    if($i==0) $hobby = $hobby_temp[$i];
    else $hobby = $hobby .', '.hobby_temp[$i] ;
}

答案 1 :(得分:0)

您在每个循环中覆盖$hobby,而应该连接变量

$hobby = '';
for($i = 0; $i < size; $i++)
{
    $hobby .= $hobby_temp[$i] . ',';
}
$hobby = substr_replace($hobby, '', -1);

答案 2 :(得分:0)

使用implode

$hobby = isset($_POST["hobby"])?implode(",",$_POST["hobby"]):"");