Get checked Checkboxes value with PHP

The checkbox element in HTML allows us to select multiple items from the group of values.

When you use it in your form and try to read all checked values as any other elements like –  text box, text area, radio button etc.

echo $_POST['lang'];  // Checkbox element

you will get the last checked value.

You need to send the checkboxes value in the form of an Array when the form gets submitted then you can loop over $_POST values.

Get checked Checkboxes value with PHP


Contents

  1. Read $_POST checked values
  2. Completed Code
  3. Conclusion

 

1. Read $_POST checked values

HTML

While creating multiple checkboxes add [] at the end of name attribute e.g. lang[]. Here, [] denotes an Array.

<span>Select languages</span><br/>
<input type="checkbox" name='lang[]' value="PHP"> PHP <br/>
<input type="checkbox" name='lang[]' value="JavaScript"> JavaScript <br/>
<input type="checkbox" name='lang[]' value="jQuery"> jQuery <br/>
<input type="checkbox" name='lang[]' value="Angular JS"> Angular JS <br/>

PHP

When the form submitted then loop over $_POST checkbox name using foreach.

if(isset($_POST['submit'])){

    if(!empty($_POST['lang'])) {    
        foreach($_POST['lang'] as $value){
            echo "value : ".$value.'<br/>';
        }
    }

}

In above code, I am displaying checked values.


 

2. Completed Code

Here, is the complete code which I explained above.

<form method="post" action="">
    <span>Select languages</span><br/>
    <input type="checkbox" name='lang[]' value="PHP"> PHP <br/>
    <input type="checkbox" name='lang[]' value="JavaScript"> JavaScript <br/>
    <input type="checkbox" name='lang[]' value="jQuery"> jQuery <br/>
    <input type="checkbox" name='lang[]' value="Angular JS"> Angular JS <br/>

    <input type="submit" value="Submit" name="submit">
</form>

<?php
if(isset($_POST['submit'])){

    if(!empty($_POST['lang'])) {

        foreach($_POST['lang'] as $value){
            echo "value : ".$value.'<br/>';
        }

    }

}
?>

 

3. Conclusion

Next time when you use multiple checkboxes in your form just initialize name as an Array by putting [] in front and read it loop when submitted.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *