Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Maddening if.else in a for loop

12:57 am on May 31, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Hello, all.

I have what I thought was a very simple for loop that cycles 5 times, then uses a very simple if..else to compare the numerical value of the current loop against the values in an array. If the two match, it packs a certain line of html into an array before looping again. If it doesn't match, it packs a different line of html into the array and loops again.

Here's the code:

for($n=1;$n<6;$n++) {
$name = //the name value;
$value = //an array of several integers;
foreach($value as $val) {
if($val == $n) {
//Add checked checkbox code to array
$hsa_inputs[$n] = "<input type='checkbox' name='$name' value='$val' checked='checked' />";
//Add unchecked checkbox code to array
$hsa_inputs[$n] = "<input type='checkbox' name='$name' value='$n' />";
}//end foreach
}//end for

The problem is that when the script runs, only the LAST value in the $value array is cranking out the "checked checkbox" html code.

I plugged a print_r($val) inside the if...else to make sure that the $values array contains the numbers it should, and it is showing the correct (and multiple) values that belong there, yet the first value is still adding the "unchecked checkbox" html.

Does anybody see anything blaringly wrong that might be the cause of this weird behavior? It seems like such a basic script and yet it is driving me insane. Please help.

2:52 am on May 31, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member


Replaced foreach with an if(in_array()) and it works fine. Foreach was looping for every match in the array and overwriting the first found result.
6:06 am on May 31, 2014 (gmt 0)

you overwrite in $hsa_inputs[$n] the values in each check ...
if $values = array(1,2);

first iteration adds the checked input, and second iteration of inner loop change that to unchecked input. in_array is the better solution but if you need it someday, here is the correct version:

for($n=1; $n<6; $n++) {

$name = 'name'; //the name value;
$value = array(1, 3); //an array of several integers;

$found = false;
foreach($value as $val) {
if($val == $n) {
$found = true;

if($found) {
$hsa_inputs[$n] = "<input type='checkbox' name='$name' value='$val' checked='checked' />";
} else {
$hsa_inputs[$n] = "<input type='checkbox' name='$name' value='$n' />";

12:54 pm on May 31, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Thanks, derfmann. Your explanation makes it clear where my thinking went off-track. I really appreciate your solution.

Featured Threads

Hot Threads This Week

Hot Threads This Month