Rob
Rob

Reputation: 6380

If checkbox group isn't ticked error is returned

I have 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.

Upvotes: 0

Views: 156

Answers (6)

jaxxstorm
jaxxstorm

Reputation: 13271

Just validate with an if statement?

foreach ($_SESSION['CheckboxGroup1'] as $val) {
if ($val !==""){
$checkbox1results .= $val.",\n";
} else {
echo "Please tick an option";
}

Upvotes: -1

Michael Roosing
Michael Roosing

Reputation: 69

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";
    }
}

Upvotes: 0

Brandon Frohbieter
Brandon Frohbieter

Reputation: 18139

just use...

if(isset($_SESSION['CheckboxGroup1'])){
   foreach ($_SESSION['CheckboxGroup1'] as $val) {
   $checkbox1results .= $val.",\n";
   }
}

Upvotes: 0

tsadiq
tsadiq

Reputation: 402

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

Upvotes: 0

David Gillen
David Gillen

Reputation: 1172

if( is_array($_SESSION['CheckboxGroup1']) ){
    foreach ($_SESSION['CheckboxGroup1'] as $val) {
        $checkbox1results .= $val.",\n";
    }
}

Upvotes: 2

Gaurav
Gaurav

Reputation: 28755

if(isset($_SESSION['CheckboxGroup1'])){     // add && is_array($_SESSION['CheckboxGroup1']) to check its an array or not
   foreach ($_SESSION['CheckboxGroup1'] as $val) {
     $checkbox1results .= $val.",\n";
   }
}

Upvotes: 1

Related Questions