Checking if Checkbox is checked in Array

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
reyes99
Forum Commoner
Posts: 38
Joined: Tue May 22, 2007 10:35 pm

Checking if Checkbox is checked in Array

Post by reyes99 »

Hi all,

I have been trying to figure this out for a few days already and can't seem to figure it out. I want to display a few images with a checkbox next to it so I can delete multiple images at once when I press the delete button.

My problem is that I can't seem to figure out how to check if the checkbox is checked. if I uncheck one of them and click the delete button it deletes one from the array but I don't know which one was unchecked. For example if I uncheck the second one the array shows:

Array
(
[0] => on
[1] => on
)

but I don't know which of the three was unchecked?

Here is the code I have so far:

Code: Select all

<?php
// if submit button is clicked
if(isset($_POST['submit'])) {
// do delete function();

}
// display deletethis[] array
if (isset($_POST['deletethis'])) {
echo "<pre>";
print_r ($_POST['deletethis']);
echo "</pre>";
}

$separate = array("http://funnypicturesimages.com/images/image/funny-dog-pictures.jpg", "http://1.bp.blogspot.com/-35wQMpYtNZc/TXWNx8y2xCI/AAAAAAAB_2o/9vZYNfWrGn8/s400/funny_demotivational_posters_01.jpg", "http://3.bp.blogspot.com/-TFnzZ8zFtgg/TXWNpodBkGI/AAAAAAAB_2Q/O_fOOSqFM6w/s400/funny_demotivational_posters_04.jpg");
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';

// display each image from array
foreach ($separate as $value)
{
	echo "<img src=".$value.">";
	if ($_POST['deletethis'] = "on") {
	  $checked="checked";
	} else {
	  $checked="";
	}
	
	if ($_POST['deletethis'] != "") {
	echo "checked"; } else{ echo "unchecked"; }
	
	// if checkbox currently checked display it checked else display unchecked
	if ($checked == "checked") {
		echo '<input type="checkbox" name="deletethis[]" checked="checked"/><br /><br />';
	} else {
		echo '<input type="checkbox" name="deletethis[]"/><br /><br />';
	}

}
?>
<center><input type="submit" name="submit" value="Delete Checked"></center>
</form>
reyes99
Forum Commoner
Posts: 38
Joined: Tue May 22, 2007 10:35 pm

Re: Checking if Checkbox is checked in Array

Post by reyes99 »

Is this possible in PHP?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Checking if Checkbox is checked in Array

Post by Celauran »

Your checkboxes should have the image ID as a value. Once the form has been posted, you can just loop through them using a foreach loop and delete as you go.
Post Reply