Чекбокс в PHP
Давайте теперь научимся работать с флажками checkbox в PHP. Сделаем такой флажок в нашей форме:
После отправки формы в $_GET флажка будет содержаться строка ‘on’ , если флажок был отмечен и null , если нет:
Давайте выведем что-нибудь на экран в зависимости от того, был отмечен флажок или нет:
Сделайте форму с инпутом и флажком. С помощью инпута спросите у пользователя имя. После отправки формы, если флажок был отмечен, поприветствуйте пользователя, а если не был отмечен — попрощайтесь.
Нюансы
Пусть в нашей форме есть только чекбокс:
Пусть код обработки нашей формы выглядит вот так:
Нас ждет проблема — если флажок не отмечен, то, так как в форме кроме чекбокса нет других элементов, в $_GET будет лежать пустой массив. Это значит, что в коде обработки формы мы не попадем в первый if , проверяющий отправку формы.
Для решения проблемы используют специальный прием: создают скрытый инпут с таким же именем, как и у нашего чекбокса. При этом значением скрытого инпута ставят ноль, а чебокса — единицу:
В таком случае получится следующее. Если чекбокс не отмечен, то на сервер отправится только значение скрытого инпута. Если же чекбокс отмечен, то на сервер отправятся оба значения с одним именем. Но, так как значение чекбокса будет вторым, то оно просто затрет первое.
Итак, теперь наша чекбокс будет отправлять на сервер или ноль, или один:
Используем это в нашей проверке:
С помощью флажка спросите у пользователя, есть ему уже 18 лет или нет. Если есть, разрешите ему доступ на сайт, а если нет — не разрешите.
Сохранение значения после отправки
Давайте теперь сделаем так, чтобы значение чекбокса сохранялось после отправки. Для этого проверим, что $_GET[‘flag’] существует (то есть была отправка формы) и равен единице (то есть флажок отмечен).
Если эти два условия выполняются, то выведем в чекбоксе атрибут checked :
Проверку можно упростить, если мы точно знаем, что скрытый инпут передает 0 . В таком случае, если чекбокс не отмечен, то в $_GET[‘flag’] будет лежать ‘0’ , а если отправки формы еще не было, то будет лежать null .
В обоих этих случаях мы не должны выводить checked . И оба этих случая мы можем поймать функцией empty . Таким образом мы можем проверить, что $_GET[‘flag’] не пуст, и только в этом случае вывести checked :
Сделайте три чекбокса, которые будут сохранять свое значение после отправки.
Как проверить checkbox php
Using isset() Function
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases. This problem can be solved with the help of isset() function.
Syntax:
Description: This function accepts more than one parameters. The first parameter of this function is $var. This parameter is used to store the value of variable.
How to Read Whether a Checkbox is Checked in PHP
In this tutorial, you can find comprehensive information on how to read whether a checkbox is checked in PHP.
Here, we will demonstrate two handy functions that will assist you in reading whether a checkbox is checked in PHP. Those functions are isset() and empty() .
Applying the isset() Function
This is an inbuilt function that is capable of checking whether a variable is set.
With the isset() function, you can also check whether an array, a declared variable, or an array key is null. The isset() function returns false if it does and true in all the possible situations.
The syntax of the isset() function looks like this:
Now, let’s see the code that will check whether a checkbox is checked:
The output of this code will show that option 1 is successfully submitted.
Applying the empty() Function
In this section, we will illustrate another inbuilt function: the empty() function.
Read if Checkbox Is Checked in PHP
We will demonstrate how to check whether the checkbox is checked in PHP using the isset() function on $_POST array. We provide the value of the name attribute of the input tag of HTML as the array element in the $_POST array.
Please enable JavaScript
We will introduce another method to read the checkbox if it is checked in PHP using the in_array() function. We use checkboxes as an array in this method. It means that the all name field in HTML input tag must contain the same array.
We will introduce a short-hand method to check if the checkbox is checked using the ternary operator. The method is more straightforward and shorter and uses the isset() function.
Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
We can use the isset() function to check whether the checkbox is checked in PHP. The isset() function takes the $_POST array as argument. The $_POST array contains the specific value of the name attribute present in HTML form.
For example, create a form in HTML with POST method and specify the action to index.php . Create two checkboxes with names test1 and test2 , respectively. Save the file with .php extension. Create a PHP file named index.php . Apply two if conditions to isset() function with $_POST array as argument. Use test1 and test2 as the array elements in the $_POST arrays, respectively. Print the message specifying the respective value has been checked.
The example below uses the POST method to send the data in the form. It is secure while sending sensitive information through the form. Click here to know more about the POST method. The user checks both the checkbox in the form. Thus, the script outputs the way it is shown below. If the user had checked only the Option 1 , the script would output as checked value1 . It goes similar to Option 2 too.
Use the in_array() Function to Read if the Checkbox Is Checked for Checkboxes as an Array
We can use the in_array() function to check whether an element lies within an array in PHP. The in_array() function takes the value to be checked as the first argument. The second argument of the function is the array where the value is to be checked. Check the PHP manual to know more about the in_array function. For this method to work, all the name attribute values in HTML form must be an array.
For example, assign the value of name attribute in HTML form with test[] array. Note it applies to all the checkbox type . First, in the PHP file, check whether the data has been submitted using the isset() function as done in the first method. But, do not use the [] brackets after the test while checking the posted data. Then, use in_array() function to check whether the value1 is in the $_POST[‘test’] array. Display the message.
At first, the example below checks whether the data is submitted in the form. If the condition is true, then it checks if value1 lies in the $_POST[‘test’] array using the in_array() function. The user checks the first checkbox in the form.
Use the isset() Function With Ternary Function to Read if the Checkbox Is Checked
We can use a short-hand method to check if the checkbox has been checked in PHP. This method uses a ternary operator along with the isset() function. Please check the MSDN Web Docs to know about the ternary operator.
For example, set a variable $check to store the value of the ternary operation. Use the isset() function to check whether test1 has been checked in the checkbox. Print $check variable to show the result. In the example below, checked is displayed if the condition is true, and the unchecked is displayed if the condition is false. The user checks the second checkbox in the form. Therefore, the condition fails.