Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm checking whether a checkbox should be checked against a user preferences array of id's with:

if(in_array($category['id'], $checkedarray)){
  $checked = "checked='checked'";
}

the result of checked array looks something like:

array(43) {
[0]=>
string(2) "31"
[1]=>
string(2) "32"
[2]=>
string(2) "34"
[3]=>
string(2) "35"
}

In the above array example, 33 still returns true even though its not in there.

I've tried using:

(in_array($category['id'],$checkedarray, true)

The results were same as without the strict condition.

Any suggestions would be greatly appreciated.

share|improve this question
can u upload it to code pad, the exact test case – Somesh Mukherjee Feb 15 '12 at 17:30
1  
The if block is missing a ) before the opening {. I'm guessing that was just an error in translation? – crush Feb 15 '12 at 17:32
sorry that was a typo, i retyped here instead of copy/paste. I'll change it in a sec, but it does have proper brackets, else it'd returns errors. – Mike Feb 15 '12 at 17:33
This works fine as shown. Can you show us the exact case that caused the problem? I ran your code at a site called Ideone, you can upload an example there, too. ideone.com/FaMiw – Rocket Hazmat Feb 15 '12 at 17:37
Ok, just a silly double check since I can't see a possible else resetting $checked, you don't happen to be declaring $checked outside the loop and forgetting to reset it the next time around the loop? – Joachim Isaksson Feb 15 '12 at 17:39
show 2 more comments

1 Answer

up vote 2 down vote accepted

33 does NOT return true -- you're simply never resetting your $checked variable.

if (true) { $checked = "checked" };
if (false) { /* never gets executed */ }

add an else!

if (in_array(33, $checkedarray)) {
    $checked = "checked='checked'";
} else {
    $checked = "";
}
share|improve this answer
I feel like a tool, made the assumption that a blank else condition pretty much did that. – Mike Feb 15 '12 at 17:46
I had an else, but it was blank, as in }else{ //} – Mike Feb 15 '12 at 17:47
Don't beat yourself up. The only reason I know this is because I've been there :) – Mikhail Feb 15 '12 at 18:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.