If checkbox group isn't ticked error is returned
I ha开发者_StackOverflow中文版ve a checkbox group which works fine when you tick one but it returns an error if all are left unticked.
Here's the code:
foreach ($_SESSION['CheckboxGroup1'] as $val) {
$checkbox1results .= $val.",\n";
}
This is the error I'm getting back:
Warning: Invalid argument supplied for foreach() in
/home/medicom/public_html/memberappform1.php on line 492
I'm not great with php so need a way to return nothing in the loop if nothing is ticked.
if( is_array($_SESSION['CheckboxGroup1']) ){
foreach ($_SESSION['CheckboxGroup1'] as $val) {
$checkbox1results .= $val.",\n";
}
}
if(isset($_SESSION['CheckboxGroup1'])){ // add && is_array($_SESSION['CheckboxGroup1']) to check its an array or not
foreach ($_SESSION['CheckboxGroup1'] as $val) {
$checkbox1results .= $val.",\n";
}
}
try to var_dump() your session to see what's inside :) Most likely the value is set but not an array, so you could use the is_array() function to check your value
just use...
if(isset($_SESSION['CheckboxGroup1'])){
foreach ($_SESSION['CheckboxGroup1'] as $val) {
$checkbox1results .= $val.",\n";
}
}
You have to check if the checkbox isset because empty checkboxes dont post values
if(isset($_SESSION['CheckboxGroup1']) {
foreach($_SESSION['CheckboxGroup1'] as $val) {
$checkbox1result .= $val.", \n";
}
}
Just validate with an if statement?
foreach ($_SESSION['CheckboxGroup1'] as $val) {
if ($val !==""){
$checkbox1results .= $val.",\n";
} else {
echo "Please tick an option";
}
精彩评论