0

How do i iterate over the $departments array and test to see if it equals the $name variable value and return "checked" if its in the list. departments is an array of checkboxes

function isChecked($name) {
$departments = (isset($_POST["interests"])) ? $_POST["interests"] : array();
foreach ($departments as $key => $value) {
    // this next line here is wrong 
    if($departments[$key][$value] == $name) { 
        return "checked";   
    };      
}
return "";

}

2
  • What does your form look like? Is it the key or the value you are testing? Commented Feb 16, 2013 at 3:37
  • related to your last question. This code won't work. I think the code of the last question was correct. Commented Feb 16, 2013 at 3:37

4 Answers 4

1

You're referring to the $value wrong inside the foreach loop. $value contains just what it says, the value of what is inside the $departments array.

function isChecked($name) {
$departments = (isset($_POST["interests"])) ? $_POST["interests"] : array();
foreach ($departments as $key => $value) {
    if($value == $name) { 
        return "checked";   
    };  
}
return "";
}
Sign up to request clarification or add additional context in comments.

Comments

1

instead of if($departments[$key][$value] == $name)

use

if($value == $name)

Comments

0

You want to use either

if ($departments[$key] == $name) { ... }

or

if ($value == $name) { ... }

$department[$key] gives you the value at $key in the $department array, but that value is also helpfully stored in $value since you set it up in the loop definition.

Comments

0

Try this.

function isChecked($name) {
    return isset($_POST['interests'][$name]);
}

If you need the function to return the string value checked if true, you can do this.

return isset($_POST['interests'][$name]) ? 'checked' : '';

Comments

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.