PHP - examples - 08 : isset(), self, this, ...

Revision:


isset() function

The isset() function can be used to check whether the checkbox is checked in PHP. It takes the $_POST array as argument, which contains the specific value of the name attribute present in HTML form.

male female

codes:
            <form action="#" method="post">
                <input type="checkbox" name="gender" value="male"/>male
                <input type="checkbox" name="gender" value="female"/>female
                <input type="submit" name="submit" value="submit"/>
            </form>
            <?php
                if(isset($_POST['gender'])){
                    echo $_POST['gender'];
                }
            ?>
        

to get value of multiple checked checkboxes

The name attribute in HTML "input type="checkbox" tag must be initialized with an array. To do this, write "[]" at the end of it's name attribute.






code:
            <div>
                <form action="#" method="post">
                    <input type="checkbox" name="check_list[]" value="C/C++"/><label>C/C++</label><br> 
                    <input type="checkbox" name="check_list[]" value="Java"/><label>Java</label><br> 
                    <input type="checkbox" name="check_list[]" value="PHP"/><label>PHP</label><br>
                    <input type="checkbox" name="check_list[]" value="HTML"/><label>HTML/CSS</label><br>
                    <input type="checkbox" name="check_list[]" value="UNIX/LINUX"><label>UNIX/LINUX</label>

                    <input type="submit" name="submit" value="submit"/>
                </form>
                <?php
                    if(isset($_POST['submit'])){//to run PHP script on submit
                        if(!empty($_POST['check_list'])){
                            //loop to store and display values of individual checked boxes
                            foreach($_POST['check_list'] as $selected){
                                echo $selected."<br>";
                            }
                        }   
                    }
                ?>
            </div>
        

use the isset() function with ternary function

Option 1
Option 2
unchecked
code;
            <div>
                <form action="php-checkboxes.php" method="post" >
                    <input type="checkbox" name="test1" value="value1"> Option 1<br>
                    <input type="checkbox" name="test2" value="value2"> Option 2<br>
                    <input type="submit" value="Submit"> 
                </form>
                <?php
                $check = isset($_POST['test1']) ? "checked" : "unchecked";
                echo $check;
                ?>
            </div>
        

PHP self vs. this


Toy: , Category:
Shop Name: Disney