0

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.

2
  • "Now i want after finishing while loop my $checkbox variable should have an empty string." There is no $checkbox variable. Commented Sep 18, 2018 at 9:47
  • Sorry. i meant $radioChecked) i have updated the same Commented Sep 18, 2018 at 9:49

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for reply. The problem is $total_radios is not an array . it is an integer.
foreach (range(0, $total_radios - 1) ... then :)
Thank you very much. Looks like this is also a good solution. i Will give a try sure. Thank you for the answer. )
1

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.

1 Comment

I am using Laravel blade i just recreated this scenario to understand better.
0

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 = '';
    }
}

1 Comment

You're missing ?> before the <input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.