How to get values of checkboxes?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adilmarwat2004
Forum Commoner
Posts: 44
Joined: Fri Sep 04, 2009 11:28 pm

How to get values of checkboxes?

Post by adilmarwat2004 »

I have three checkboxes like that

<from>
<input type="checkbox" name="news" value="Aaj">Ajj
<input type="checkbox" name="news" value="Express">Express
<input type="checkbox" name="news" value="Dawn">Dawn
<input type="submit" value="Send">
</form>

Now I want that how I get the values of the selected checkbox values in the next page of php. please help.
siko
Forum Commoner
Posts: 37
Joined: Tue Feb 16, 2010 11:28 pm

Re: How to get values of checkboxes?

Post by siko »

Are you trying to store those values in an array?

If so, you have to do:

<input type="checkbox" name="news[]" value="Aaj">Ajj
<input type="checkbox" name="news[]" value="Express">Express
<input type="checkbox" name="news[]" value="Dawn">Dawn

Add the [] at the end of the field name, and on the next page, access them by $_POST["news"].

It will be in an array though, so you can do something like

$news = $_POST["news"];

echo news[0];
echo news[1];
adilmarwat2004
Forum Commoner
Posts: 44
Joined: Fri Sep 04, 2009 11:28 pm

Re: How to get values of checkboxes?

Post by adilmarwat2004 »

I do that in html
<form method="post" action="edu.php">
<input type="checkbox" name="news[]" value="Aaj">Ajj
<input type="checkbox" name="news[]" value="Express">Express
<input type="checkbox" name="news[]" value="Dawn">Dawn
<input type="submit" value="Send">
</form>


edu.php

<?php
$edu = $_POST['edu'];
$news = $_POST["news"];

echo "Your Education is ". $edu." Your Newspaper is ".$news[0]." ".$news[1]." ".$news[2];

?>

When I select two check boxes and then send it gives results and also error line like that

Notice: Undefined offset: 2 in C:\wamp\www\Test\edu.php on line 5
Your Education is MSc Your Newspaper is Express Dawn

Now please help how to solve the problem at line 5 code.
siko
Forum Commoner
Posts: 37
Joined: Tue Feb 16, 2010 11:28 pm

Re: How to get values of checkboxes?

Post by siko »

On your edu.php page, $_POST["news"] only have 2 items, because you only checked 2 of the checkboxes.

PHP doesnt keep track of what you DIDN'T check. It only stores what you DID check.

Therefore, $news[2] does not exist in the particular example you gave here.
Post Reply