Reputation: 5859
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 "";
}
Upvotes: 0
Views: 48
Reputation: 801
instead of if($departments[$key][$value] == $name)
use
if($value == $name)
Upvotes: 1
Reputation: 21130
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' : '';
Upvotes: 0
Reputation: 900
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.
Upvotes: 0
Reputation: 4301
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 "";
}
Upvotes: 1