1

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.

7
  • can u upload it to code pad, the exact test case Commented Feb 15, 2012 at 17:30
  • 1
    The if block is missing a ) before the opening {. I'm guessing that was just an error in translation? Commented Feb 15, 2012 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. Commented Feb 15, 2012 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 Commented Feb 15, 2012 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? Commented Feb 15, 2012 at 17:39

1 Answer 1

2

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 = "";
}
Sign up to request clarification or add additional context in comments.

3 Comments

I feel like a tool, made the assumption that a blank else condition pretty much did that.
I had an else, but it was blank, as in }else{ //}
Don't beat yourself up. The only reason I know this is because I've been there :)

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.