Processing Checkboxes using PHP

Hello all.

I’m attempting learn a better way to post checkboxes into variables, the way I used to do it was long and tedious as I used to post each checkbox into its own variable, like this.

$checkbox1 = $_POST['checkbox1'];
$checkbox2 = $_POST['checkbox2'];
$checkbox3 = $_POST['checkbox3'];

I am attempting to create a loop that processes all the checkboxes and assigns them a variable with a number after it, such as $checkbox1.

 <input type="checkbox" name='position[]' value="investmentstrategies" checked="yes" align="left">

That’s how my checkboxes are set up and this is the code I have tried out.


if (isset($_POST['position'])) 
{
	foreach ($_POST['position'] as $position) 
	{
	$i=0;
	$checkbox[$i] = $position
	$i++
	}
}

I’ve hit a brick wall, if anyone could help me out it would be much appreciated.


I’d do something like this:

 

$checkbox = array();

if(isset($_POST['position'])) {
  foreach($_POST['position'] as $position) {
  array_push($checkbox, $position);
 }
}


mystline7, what does this $i=0; inside of a loop?

Also, remember, you can always use operator, without any counters

Uhh not really sure :blush:

I’m trying hifigrafix’s suggestion, but despite having all the checkboxes ticked it’s only resulting in the script echo’ing “Array”

My current code is as follows:


$checkbox_all = array();

if(isset($_POST['position'])) {
  foreach($_POST['position'] as $checkbox_single) {
  array_push($checkbox_all, $checkbox_single);
 }
} 
echo $checkbox_all

I think it might be because you can’t echo arrays like that, but I’m not sure, as I’ve had little experience with them

The HTML checkboxes haven’t changed btw :slight_smile:

Yes, it is because you can’t echo arrays like that.

Also, I can suggest you another way to do it:

if (isset($_POST['position'])) 
{
    $checkbox=$_POST['position'];
}

Uhh not really sure

Try to think. That’s what I am doing in such case.
What does all these strange hieroglyphs mean

I had previously set up a loop that used $i to add numbers to values, similar to the example i’ll post below, but had trouble actually assigning the values to individual variables, I think the $i was left over perhaps, I’m not 100% sure, i’ve been trying to solve this problem on and off for a day or two now.


if (count($position)<0) {
        echo("Nothing chosen");
     }
     for ($i=0; $i<count($position); $i++) {
        echo( ($i+1) . ") " . $position[$i] . "<br>");
    }

Where abouts would I be able to find some decent reading on how arrays work? I have the concept I think, just not the know-how to use them correctly in PHP.

Also could you explain how your example will work? as I’ll need to have the checkboxes assigned to individual variables :slight_smile:

You need an article on programming basics - loops, conditions, variables. Not on arrays.
Because your fault is in variables, not in arrays.

    foreach ($_POST['position'] as $position) 
    {
      $i=0;
      echo $i."<br>";
      $i++
    }

What output you expect from this code? Incrementing numbers?

Also could you explain how your example will work?

Sure. It does the same, what your code tries to.

I’ll need to have the checkboxes assigned to individual variables

I doubt you really need it.

Righto, I’ll try out yours. The reason I require them in separate variables is because the information is going to be mailed to different people, depending on what is checked. I was planning on just using a few basic ‘if’ statements further on. Is there a better way of doing this that I’m not aware of?

You can use array members as well as scalar variables.

$checkbox=$_POST['position'];
if (isset($checkbox[0])) //first checked
if (isset($checkbox[1])) //second checked
// etc

That’s perfect. Exactly what I was looking for, thanks alot!

I’d recommend using array keys. If you use and refer to checkboxes as first,second, third etc and you decide to change the order in the markup then your backend code will start silently referring to the wrong checkboxes. Also if not all are checked the alignment will go wacky.


<input type="checkbox" name="checkbox[tv]">
<input type="checkbox" name="checkbox[stereo]">
<input type="checkbox" name="checkbox[fridge]">
<input type="checkbox" name="checkbox[sofa]">


if(isset($_POST['checkbox'])) {
   foreach($_POST['checkbox'] as $key => $value) {
      //checked checkboxes will be defined
      //e.g $key = tv
    }
}

I’m trying to generate similar results to post from a form to a formmail. I have the following:

<label for="hearDog">2. How did you hear about this particular dog(s)?</label>
<?php if (isset($error['hearDog'])) { ?>
<span class="warning"><?php echo $error['hearDog']; ?></span>
<?php } ?>
<br />
<input type="checkbox" name="hearDog[]" value="Petfinder.org" id="Petfinder" />
<label for="Petfinder.org">Petfinder.org</label>
<input type="checkbox" name="hearDog[]" value="Pets911" id="Pets911" />
<label for="Pets911">Pets911</label>
<input type="checkbox" name="hearDog[]" value="Noah's Friends Website" id="NoahFriends" />
<label for="NoahFriends">Noah's Friends Website</label>
<input type="checkbox" name="hearDog[]" value="Breed Rescue Site" id="breedrescue" />
<label for="breedrescue">Breed Rescue Site</label> 

I assume that by the example above (making minor modifications),

$hearDog = $_POST['hearDog'];
if(isset($_POST['hearDog'])) {
foreach($_POST['hearDog'] as $key => $value) {
}
if (empty($hearDog)) {
$error['hearDog'] = 'Please choose how you heard about this particular dog(s)';
}
} 

and the user chooses ‘Breed Rescue Site’ and ‘Pets911’, then the email will post this:

  1. How did you hear about this particular dog(s)?
    Breed Rescue Site
    Pets911

Does this look about right?

It’s close. The foreach will want to be able to handle multiple $key and $value entries. If only one should be chosen and handled, you should use radio choices instead of checkboxes.

No, it doesn’t look about right.
You need an article on programming basics too.

Looping through an array is very similar to looking in your pockets for the coin.
Checking first pocket… Empty.
Checking another pocket… Found!
Checking third pocket… Empty.
Imagine you’re making note “Not found at all” if pocket was empty. What it would say? Not found. But you’ve got one! So, something wrong with algorithm.
Try to think about it.

But you don’t need loop at all. You can just check if variable not empty.
But.

  1. Not inside loop, because it makes no sense.
  2. Existing variable. Where variable $hearDog come from?
    So, checking would be just 3 lines:
if (empty($_POST['hearDog'])) {
$error['hearDog'] = 'Please choose how you heard about this particular dog(s)';
}

And for the array-to-text transformation you can use very useful implode() function.

You know, this seems to work:

		$hearDog = implode(", " , $_POST['hearDog']);
	if (empty($hearDog)) {
		$error['hearDog'] = 'Please tell us how you heard about this particular dog(s)?';
		}

RESULT:
2. How did you hear about this particular dog(s)?
Breed Rescue Site,

Except I get the extra comma, even if there’s only one selection (by the way, I plan on converting this to radio buttons, but I believe this to be useful later on in my form). Any way there’s a function to exclude the comma if there’s only one selection or when there’s a last selection? Or am I asking for something more complicated?

Thanks for the useful lesson!