Add checked="checked" if selected (foreach loop)

Here is some code I’m using for a web form. As you can see it uses a foreach loop to create the form fields. I now need to add checked=“checked” for those options selected but don’t know how to. Any help?

$outsource2 = array("Marketing Agency","PR Agency","Design Studio","Marketing Consultant", "Media Agency", "Advertising Agency", "Service or Product Design Agency", "Customer Experience Agency");

  if($_SERVER['REQUEST_METHOD'] == 'POST') {


	    if(isset($_POST['outsource'])){
        foreach($outsource2 as $outsource){
                  $value = (in_array($outsource,$_POST['outsource']) ? "True" : "False");
               $_SESSION[$outsource] = $value;
                $result[$outsource] = $value;
        }
}		
		else {
      unset($_SESSION['outsource']);	
		}

}

$outsourceoptionsOutput = "";
        foreach($outsource2 as $outsource){
            $outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\" value=\\"". $outsource ."\\">". $outsource ." &nbsp;\\r";
        }
$outsourceoptionsOutput .= "<br />"; 

you foreach loop will be as


foreach($outsource2 as $outsource)
{
            if ($outsource == $outsource_selected)
                     $checked = ' checked="checked" ';
            else
                     $checked = '';
            $outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\"    ".$checked."     value=\\"". $outsource ."\\">". $outsource ." &nbsp;\\r";
}

OR

foreach($outsource2 as $outsource){
	$checked = (isset($outsource_selected) && $outsource == $outsource_selected ? " checked=\\"checked\\"" : '');
	$outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\"$checked value=\\"$outsource\\">$outsource &nbsp;\\r";
}

Thank you for the help both of you – especially you Drummin for helping me put together the original code (on the other thread) :smiley:

I’ve just tested it and it’s still not working. No error messages are popping up. It’s just that when the submit button has been hit, the page doesn’t keep the radio buttons and checkboxes selected. Here is my code, for five different form elements:

$marketingvalueOutput = "";
       foreach($marketingimportance2 as $marketingimportance){
			$checked1 = (isset($marketingimportance_selected) && $marketingimportance == $marketingimportance_selected ? " checked=\\"checked\\"" : '');
			$marketingvalueOutput .= "<input type=\\"radio\\" class=\\"radio\\" name=\\"marketingimportance[]\\"" . $checked1 . " value=\\"". $marketingimportance ."\\">". $marketingimportance ." &nbsp;\\r";
        } $marketingvalueOutput .= "";
		
$custexpOutput = "";
       foreach($custexpimportance2 as $custexpimportance){
			$checked2 = (isset($custexpimportance_selected) && $custexpimportance == $custexpimportance_selected ? " checked=\\"checked\\"" : '');
			$custexpOutput .= "<input type=\\"radio\\" class=\\"radio\\" name=\\"custexpimportance[]\\"" . $checked2 . " value=\\"". $custexpimportance ."\\">". $custexpimportance ." &nbsp;\\r";
        }
$custexpOutput .= "";

$marfuOutput = "";
        foreach($marfu2 as $marfu){
			$checked3 = (isset($marfu_selected) && $marfu == $marfu_selected ? " checked=\\"checked\\"" : '');
			$marfuOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"marfu[]\\"" . $checked3 . " value=\\"". $marfu ."\\">". $marfu ." &nbsp;\\r <br />";
        }
$marfuOutput .= "";

$custexpoptionsOutput = "";
        foreach($custexpoptions2 as $custexpoptions){
			$checked4 = (isset($custexpoptions_selected) && $custexpoptions == $custexpoptions_selected ? " checked=\\"checked\\"" : '');
			$custexpoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"custexpoptions[]\\"" . $checked4 . " value=\\"". $custexpoptions ."\\">". $custexpoptions ." &nbsp;\\r <br />";
        }
$custexpoptionsOutput .= "";


$outsourceoptionsOutput = "";
        foreach($outsource2 as $outsource){
			$checked5 = (isset($outsource_selected) && $outsource == $outsource_selected ? " checked=\\"checked\\"" : '');
			$outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\"" . $checked5 . " value=\\"". $outsource ."\\">". $outsource ." &nbsp;\\r <br />";
        }
$outsourceoptionsOutput .= "<br />";

I think the if statement you’ve created is not working properly. $outsource_selected doesn’t seem to be defined anywhere.

What are you doing with posted results? Updating a DB table? You would query DB table to get values such as $marketingimportance_selected before building the display section. Here’s a basic outline of a page.

<?php
//DB connection

//Post validation and Update DB table

//Query relative tables and set variables, e.g. $marketingimportance_selected

//Pre-build your output before being sent to broswer, e.g. $marketingvalueOutput

?>
<html>
<body>
<?php
if (isset($marketingvalueOutput)){ echo $marketingvalueOutput;}
?>
</body>
</html>

Ah sorry. I see that you’re saving post to session, so what you need to do is double check that session is set, check that array_key_exists for each type ($outsource etc) and check that the value matches what you’ve set it to above in processing i.e. True, False.

<?php
session_start();

//Pre-build your output before being sent to broswer, e.g. $marketingvalueOutput
$outsource2 = array("Marketing Agency","PR Agency","Design Studio","Marketing Consultant", "Media Agency", "Advertising Agency", "Service or Product Design Agency", "Customer Experience Agency");

if($_SERVER['REQUEST_METHOD'] == 'POST'){
	if(isset($_POST['outsource'])){
		foreach($outsource2 as $outsource){
			$value = (in_array($outsource,$_POST['outsource']) ? "True" : "False");
			$_SESSION[$outsource] = $value;
			$result[$outsource] = $value;
		}
	}else{
		unset($_SESSION['outsource']);
	}
}


$outsourceoptionsOutput = "";
//added for testing
$outsourceoptionsOutput .= "<form action=\\"\\" method=\\"post\\">\\r";
//end added for testing
        foreach($outsource2 as $outsource){
			$checked5 = (isset($_SESSION) && array_key_exists($outsource,$_SESSION) && $_SESSION[$outsource] == "True" ? " checked=\\"checked\\"" : '');
			$outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\"" . $checked5 . " value=\\"". $outsource ."\\">". $outsource ." &nbsp;\\r <br />";
        }
$outsourceoptionsOutput .= "<br />";

//added for testing
$outsourceoptionsOutput .= "<input type=\\"submit\\" name=\\"submit\\" value=\\"Submit\\" />\\r";
$outsourceoptionsOutput .= "</form>\\r";
?>
<html>
<body>
<?php
if (isset($outsourceoptionsOutput)){ echo $outsourceoptionsOutput;}
?>
</body>
</html>

Again looking that you have a session key of ‘outsource’ e.g. unset($_SESSION[‘outsource’]); you should probably set each session with this key, then the sub-key [$outsource] and check these during form building.

<?php
session_start();

//Pre-build your output before being sent to broswer, e.g. $marketingvalueOutput
$outsource2 = array("Marketing Agency","PR Agency","Design Studio","Marketing Consultant", "Media Agency", "Advertising Agency", "Service or Product Design Agency", "Customer Experience Agency");

if($_SERVER['REQUEST_METHOD'] == 'POST'){
	if(isset($_POST['outsource'])){
		foreach($outsource2 as $outsource){
			$value = (in_array($outsource,$_POST['outsource']) ? "True" : "False");
			$_SESSION['outsource'][$outsource] = $value;
		}
	}else{
		unset($_SESSION['outsource']);
	}
}


$outsourceoptionsOutput = "";
//added for testing
$outsourceoptionsOutput .= "<form action=\\"\\" method=\\"post\\">\\r";
//end added for testing
        foreach($outsource2 as $outsource){
			$checked5 = (isset($_SESSION['outsource']) && array_key_exists($outsource,$_SESSION['outsource']) && $_SESSION['outsource'][$outsource] == "True" ? " checked=\\"checked\\"" : '');
			$outsourceoptionsOutput .= "<input type=\\"checkbox\\" class=\\"checkbox\\" name=\\"outsource[]\\"" . $checked5 . " value=\\"". $outsource ."\\">". $outsource ." &nbsp;\\r <br />";
        }
$outsourceoptionsOutput .= "<br />";

//added for testing
$outsourceoptionsOutput .= "<input type=\\"submit\\" name=\\"submit\\" value=\\"Submit\\" />\\r";
$outsourceoptionsOutput .= "</form>\\r";
?>
<html>
<body>
<?php
if (isset($outsourceoptionsOutput)){ echo $outsourceoptionsOutput;}
?>
</body>
</html>

Hi Drummin,

Are both boxes of code essentially the same? Also, a user on another forum recommended changing the code to this:

$outsourceoptionsOutput = "";
foreach($outsource2 as $outsource){
     $outsourceoptionsOutput .= '<input type="checkbox" class="checkbox" name="outsource[]" value="' . $outsource . '"';
     if(isset($_POST['outsource']) && $_POST['outsource']==$outsource) { $outsourceoptionsOutput .= ' checked="checked"'; }
     $outsourceoptionsOutput .= ' />' . $outsource . " &nbsp;\\r";
}

This seems to work. What are the advantages of using your method over this?

Thanks

Actually ignore the code in my last post – it doesn’t work!

I’ve used your first code Drummin and that seems to work. What’s the difference between that and the second bit of code you posted? I didn’t understand the explanation.

Also, I hear you need a hidden form input for checkboxes because PHP doesn’t count it as a post when no checkboxes are selected. Any advice on this?

Thanks :slight_smile:

Your processing code is saving POST to session (I assume for adding to DB at some point) and so we are using this session data to check for “checked”. It is also saying that if you don’t have any POST for outsource, then we should unset the session data for outsource. This makes sense and that is the real difference on my second version. As far as the question on the hidden field, in this case we don’t need it.

The other big difference on my second version is that each session has a primary key. In that example the primary key is ‘outsource’, which matches the form field and so for each of those array loops, both in the form and processing we add or check for primary key or the secondary key represented by the variable $outsource $_SESSION[‘outsource’][$outsource]

This could make a big difference if for example more than one of your defining arrays has the same value, e.g. “Marketing Agency”. Without the primary key in place, e.g. $_SESSION[‘Marketing Agency’] for ‘outsource’ would be overridden by the next group. I don’t know if that makes sense to you but the second version should fix that.

Hi Drummin,

Thank you for the explanation. I’ve now started using the second piece of code.

You are correct in saying that I will be adding this to a database at some point. When I do, what PHP code would I need to get the individual values from the $_SESSION[‘outsource’] array? (for example, if I wanted to see if the first option was true or false).

Usually I would use $_SESSION[‘outsource’] == “True” but that obviously won’t work when there are multiple values.

Thanks

What is your DB table structure where these values will be added? Is it INSERT or UPDATE and what values will you use e.g. 1/0 - true/false - yes/no

I don’t know much about SQL so I’ve tried creating code that emails across the results, given that there’s no confidential data in the survey. At the moment, the last page of my survey contains this:

	$to = "xyz";
$subject = "Survey Response";
$message = print_r($_SESSION);
$from = "xyz";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);

session_destroy();
			
		header('Location: page_6.php');
		exit;

The ‘xyz’ is where my email address goes. However, even with a valid email address input, that code doesn’t seem to work. I’m wondering what I’m doing wrong.

Maybe give this a go.

$message = "";	
foreach($_SESSION as $cat => $subcat){
	$message .= "Category:" . $cat . "\
\\r";
	foreach($subcat as $c => $value){
		$message .= $c .":" . $value . "\
\\r";
	}
}
$to = "xyz@mail.com";
$subject = "Survey Response";
$from = "abcc@mail.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);

session_destroy();
			
		header('Location: page_6.php');
		exit;

Just tried it and it comes up with these errors:

Warning: Invalid argument supplied for foreach() in /home/namcocen/public_html/survey/page_5.php on line 45

Warning: Cannot modify header information - headers already sent by (output started at /home/namcocen/public_html/survey/page_5.php:45) in /home/namcocen/public_html/survey/page_5.php on line 57

Here is lines 45-57:

foreach($subcat as $c =&gt; $value){ 
    $message .= $c .":" . $value . "\

\r";
}
}
$to = “xyz@mail.com”;
$subject = “Survey Response”;
$from = “abcc@mail.com”;
$headers = “From:” . $from;
mail($to,$subject,$message,$headers);

session_destroy();

    header('Location: page_6.php'); 

Is there some sort of clash between the header() function and $headers? Or is it something else?

Thanks for your continued help with the difficult problem, by the way :slight_smile:

Are you using the second example from post #7 above?

All processing should be done BEFORE any output to browser.

What does print_r() show?

echo "<pre>";
print_r($_SESSION);
echo "</pre>"; 

When testing, I see message as

Category:outsource

Marketing Agency:False

PR Agency:False

Design Studio:False

Marketing Consultant:True

Media Agency:False

Advertising Agency:False

Service or Product Design Agency:False

Customer Experience Agency:False

Print_r shows all data collected up until that point:

Array
(
    [name] => aaa
    [email] => aa@aaa.com
    [job] => aaa
    [businessname] => aaa
    [sector] => technology
    [stores] => Yes
    [turnover] => 1
    [employees] => 1
    [businesssize] => Small Business
    [outletnumber] => 1
    [marketingemployees] => 1
    [marketingimportance] => 2
    [custexpimportance] => 2
    [marfu] => Yes
    [custexpoptions] => Array
        (
            [We are constantly looking to find new ways to improve the overall customer experience] => False
            [There is a team in the business specialising in managing the customer experience] => False
            [There is a dedicated position within the business for customer experience management] => False
            [Customer experience management is something that receives great consideration at a board/strategic level] => True
        )

    [outsource] => Array
        (
            [Marketing Agency] => True
            [PR Agency] => False
            [Design Studio] => False
            [Marketing Consultant] => False
            [Media Agency] => False
            [Advertising Agency] => False
            [Service or Product Design Agency] => False
            [Customer Experience Agency] => False
        )

    [marketingbudget] => 1
    [marketcustexpbudget] => 1
    [services] => Array
        (
            [Branding] => False
            [Print and Graphic Design] => False
            [Public Relations] => False
            [Product or Service Design] => False
            [Retail Design] => False
            [Visual Merchandising] => True
            [Marketing Strategy] => True
            [Marketing Consultancy] => False
            [Market Research] => False
            [Customer Research] => False
            [Copywriting] => False
            [Email Marketing] => False
            [Video Production] => False
            [Social Media] => False
            [Web Design and Development] => False
            [Search Engine Optimisation] => False
            [Customer Service Training] => False
            [Campaign Management] => False
            [E-commerce] => False
            [Other] => False
        )

    [agencybudget] => 1
    [review] => Weekly
    [agency] => Array
        (
            [To increase sales] => False
            [To increase brand awareness] => False
            [To make up for lack of in-house expertise & resources] => True
            [To seek fresh ideas & independent perspective] => False
            [To ensure integrated approach to marketing] => False
        )
)

This page is the final page of the survey. It has three final questions, two compulsory and one optional, then I want to send it all via email.

<?php 
session_start();

echo "<pre>"; 
print_r($_SESSION); 
echo "</pre>";  

$showlogo = TRUE;

$custexpagency2 = array ("Yes", "No");

  if($_SERVER['REQUEST_METHOD'] == 'POST') {

		if (isset($_POST['custexpagency'])) {
	$custexpagency = $_POST['custexpagency'];	
      $_SESSION['custexpagency'] = $custexpagency;
	}
	
	else {
	$custexpagencyerror = "<br /><span class=\\"feedback\\">Please select one of the options</span>";
      unset($_SESSION['custexpagency']);
	}

    $freeform1 = isset($_POST['freeform1']) ? trim($_POST['freeform1']) : FALSE ;
    
    if(empty($freeform1)) {
      unset($_SESSION['freeform1']);
      
    } else {
	  stripslashes($freeform1);
      $_SESSION['freeform1'] = $freeform1;
    }

    $freeform2 = isset($_POST['freeform2']) ? trim($_POST['freeform2']) : FALSE ;
    
    if(empty($freeform2)) {
      unset($_SESSION['freeform2']);
      
    } else {
	  stripslashes($freeform2);
      $_SESSION['freeform2'] = $freeform2;
    }
	
			if(isset($_SESSION['custexpagency'])) {
			
$message = "";     
foreach($_SESSION as $cat => $subcat){ 
    $message .= "Category:" . $cat . "\
\\r"; 
    foreach($subcat as $c => $value){ 
        $message .= $c .":" . $value . "\
\\r"; 
    } 
} 
$to = "xyz@mail.com"; 
$subject = "Survey Response"; 
$from = "abcc@mail.com"; 
$headers = "From:" . $from; 
mail($to,$subject,$message,$headers); 

session_destroy(); 
             
        header('Location: page_6.php'); 
        exit;  
		}
	
	
	}

	$custexpagencyOutput = ""; 	
foreach($custexpagency2 as $custexpagency){ 
     $custexpagencyOutput .= '<input type="radio" class="radio" name="custexpagency" value="' . $custexpagency . '"';
     if(isset($_POST['custexpagency']) && $_POST['custexpagency']==$custexpagency) { $custexpagencyOutput .= ' checked="checked"'; }
     $custexpagencyOutput .= ' />' . $custexpagency . " &nbsp;\\r";	 
}
$custexpagencyOutput .= "" .  (isset($custexpagencyerror) ? $custexpagencyerror : "") . ""; 

$content = "<div id=\\"padding\\"><div id=\\"progress-bar\\">
    <div id=\\"progress-bar-percentage\\" style=\\"width: 90%\\"></div>
</div>
<div class=\\"percentage\\">90% complete</div>
<hr />
<h2>Customer Experience Agency</h2>
<form method=\\"post\\" action=\\"page_5.php\\">
<div class=\\"questions\\">
<div class=\\"left-questions\\">
<p class=\\"question-text\\">Would you consider using a customer experience agency that could help your business with customer experience analysis, customer experience improvement and marketing communications?</p>" . $custexpagencyOutput . "
</div>
<div class=\\"right-questions\\">The following two questions are NOT compulsory: <p class=\\"question-text\\">What do you think differentiates a customer experience agency from a marketing agency?</p>
<textarea rows=\\"5\\" cols=\\"50\\" name=\\"freeform1\\">". (isset($_POST['freeform1']) ? htmlentities($_POST['freeform1']) : "") ."</textarea>
<p class=\\"question-text\\">Would you like to make any additional comments or give feedback on the survey?</p>
<textarea rows=\\"5\\" cols=\\"50\\" name=\\"freeform2\\">". (isset($_POST['freeform2']) ? htmlentities($_POST['freeform2']) : "") ."</textarea>
</div>
</div>
<p><input type=\\"submit\\" name=\\"submit\\" value=\\"Next\\"></p>
</div>
</form>
";
include('template.php'); 
?>

I’ve just made a long post showing all my code but apparently a moderator has to approve it before it will appear.

To answer your questions briefly though:

  • I used the second bit of code from your earlier post. However, it’s been slightly adapted (names of variables changed etc) as this is a multi-page survey.

  • The code you gave me is definitely working fine as print_r() shows all information collected thus far. There are three extra form elements on this final page and then when ‘submit’ is hit I want it to collect everything and send the email.

  • Perhaps that’s the problem. You said all processing has to be done before any output to browser but I’ve put this in an if statement. Does this mail() code have to be at the top of the page then?

Approved.
Sorry about that, I don’t know why that post got flagged.

It needs to be done before anything is sent to browser, echo, print, html etc.

Those extra form elements can be added to the message variable, $message .= “My Extra Message”;