Page 1 of 1

Checking if Checkbox is checked in Array

Posted: Mon May 14, 2012 7:05 am
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>

Re: Checking if Checkbox is checked in Array

Posted: Mon May 14, 2012 12:17 pm
by reyes99
Is this possible in PHP?

Re: Checking if Checkbox is checked in Array

Posted: Mon May 14, 2012 12:37 pm
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.