Creating session data based on checkbox selections

Hi there,

I’m using arrays to create checkboxes for a HTML form. Here is the code for one such array:

		  $custexp2Array = array('1' => 'We are constantly looking to find new ways to improve the overall customer experience.',
                          '2' => 'There is a team in the business specialising in managing the customer experience.',
                          '3' => 'There is a dedicated position within the business for customer experience management.',
                          '4' => 'Customer experience management is something that receives great consideration at a board/strategic level.');

  $custexp2Output = '';

  foreach($custexp2Array AS $key => $value) {

    $checked = (isset($_POST['custexp']) && is_array($_POST['custexp']) && in_array($key, $_POST['custexp'])) ? 'checked' : '' ;
    $custexp2Output .= '<input type="checkbox" class="checkbox" name="custexp[]" value="'. $key .'" '. $checked .'>'. $value .'<br />';
  }

What I now need to do is to get all the checkboxes that have been checked, turn that into a variable and convert that into a session.

I imagine I’d need to use an if statement (ie if($_SERVER[‘REQUEST_METHOD’] == ‘POST’) ) but what code needs to be included in that statement?

This problem has been troubling me all day so I’d appreciate any help :slight_smile:

Here’s two versions. The first gives you an array which I think would be easier to use.

<?php
session_start();
					
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	if(isset($_POST['custexp'])){
		foreach($_POST['custexp'] as $custexp){
			if(!isset($_SESSION['custexp']) || isset($_SESSION['custexp']) && !in_array($custexp,$_SESSION['custexp'])){
				$_SESSION['custexp'][] = $custexp;
			}
		}		
		//echo "<pre>";
		//print_r($_SESSION['custexp']);
		//echo "</pre>";
	}
}
?>

This second one names the session by the selected radio field, which is more what you were asking for.

<?php
session_start();
									
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	if(isset($_POST['custexp'])){
		foreach($_POST['custexp'] as $custexp){
			$varname = "custexp" . $custexp;			
				$_SESSION[$varname] = $custexp;
		}		
		//echo "<pre>";
		//print_r($_SESSION);
		//echo "</pre>";
	}
}
?>

Thanks for your help :smiley: