Reputation: 1320
I have situation where i want to set some value to a php variable in a while loop. Please have a look at my code for better understanding.
$radioChecked = '';
$j=1;
while($j <= $someNumber){
$radioChecked = 'checked';
$j++;
}
Now i want after finishing while loop my $radioChecked
variable should have an empty string.
Actually i am trying to do this:
i have some Radio buttons and i want to check some of them. how many checkboxes will be checked it will be depending on $someNumber
variable.
Then i have checkboxes down:
for ($i = 0; $i < $total_radios; $i++){
<input type="radio" <?php echo $radioChecked; ?> />
}
Now here is the problem:
if i have 4 $total_radios
then i am getting 4 radios displayed on the page which is good as i expecting that. If $someNumber
is 2 then i want first 2 radio buttons to be checked. If $someNumber
is 3 then i want first 3 radio buttons to be checked and so on.
But in my case it is checking all the Radio Buttons. I need some logic to reset $radioChecked
variable to empty string if condition while loop condition false.
How can i do this? Thanks.
Upvotes: 0
Views: 812
Reputation: 780818
Perform the test against $someNumber
around the echo
statement.
for ($i = 0; $i < $total_radios; $i++){ ?>
<input type="radio" <?php if ($i < $someNumber) echo $radioChecked; ?> />
<?php
}
You were also missing the ?>
and <?php
around the HTML body of the for
loop.
Upvotes: 1
Reputation: 106
I think this would also work as a solution:
for ($i = 0; $i < $total_radios; $i++){
<input type="radio" <?php echo $radioChecked; ?> />
$j--;
if ($j == 0) {
$radioChecked = '';
}
}
Upvotes: 0
Reputation: 25384
Why not just do it in the loop?
foreach ($total_radios as $i => $total){
<input type="radio" <?php if ($i < $someNumber) echo 'checked'; ?> />
}
Mish-mash between php and html but the provided example is the same.
Upvotes: 3