Reputation: 77
The default value is the first radio button.
The output like this: 1=>Y ,2=>N ,3=>N
OK, no problem.
Now my question is, I want to click the third radio button.
The expected output like this: 1=>N, 2=>N, 3=>Y
But my output like this: 1=>N, 2=>Y, 3=>Y
The second one should be N, not Y.
Here is my code:
<html>
<body>
<form action="test.php" method="post">
<?php
$defaultkey = array("Y","N","N");
for($i = 1; $i <= count($defaultkey); $i++)
{
?>
<input type="radio" name="choice" value="<?php echo $defaultkey[$i-1]; ?>"><?php echo $defaultkey[$i-1];?><br />
<?php
}
?>
<input type="submit" name="submit" value="OK" />
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
if($_POST['choice']=="Y")
{
for($j = 1; $j <=count($defaultkey); $j++)
{
echo ($j). '=>' .$defaultkey[$j-1]. '<br />';
}
}
else if($_POST['choice']=="N")
{
for($k = 1; $k <=count($defaultkey); $k++)
{
if($_POST['choice']==$defaultkey[$k-1])
{
$defaultkey[$k-1] = "Y";
echo ($k). '=>' .$defaultkey[$k-1]. '<br />';
}
else
{
$defaultkey[$k-1] = "N";
echo ($k). '=>' .$defaultkey[$k-1]. '<br />';
}
}
}
}
How should I solve it?
Upvotes: 1
Views: 1680
Reputation: 318
The problem is with:
for($k = 1; $k <=count($defaultkey); $k++)
{
if($_POST['choice']==$defaultkey[$k-1])
{
$defaultkey[$k-1] = "Y";
echo ($k). '=>' .$defaultkey[$k-1]. '<br />';
}
else
{
$defaultkey[$k-1] = "N";
echo ($k). '=>' .$defaultkey[$k-1]. '<br />';
}
}
When you check the last radio button, your choice is N. Your 2nd item in defaultkey array is N also, so when you loop through, $_POST['choice'] == $defaultkey[ 1 ] will return true before it reach the $defaultkey[ 2 ].
You have to rewrite your php logic, I don't quite understand what do you want to achieve in your code, so I can't advise you how to re-write.
Upvotes: 0
Reputation: 6253
You should know how web forms data work. Your current radio buttons are:
<input type="radio" name="choice" value="Y">Y
<input type="radio" name="choice" value="N">N
<input type="radio" name="choice" value="N">N
So you can't find out which radio button is select (1, 2, or 3). Try to change the value of them:
<?php
$defaultkey = array("Y","N","N");
for($i = 1; $i <= count($defaultkey); $i++)
{
?>
<input type="radio" name="choice" value="<?php echo $i; ?>"><?php echo $defaultkey[$i-1];?><br />
<?php
}
?>
Which generate this:
<input type="radio" name="choice" value="1">Y
<input type="radio" name="choice" value="2">N
<input type="radio" name="choice" value="3">N
And in your Submit:
<?php
if(isset($_POST['submit'])) {
for ($i = 1; $i <= count($defaultkey); $i++) {
echo $i . ' => ' . ($_POST['choice'] == $i ? 'Y' : 'N') . '<br />';
}
}
?>
Upvotes: 1