- Handling checkbox in a PHP form processor
- Single check box
- Check box group
- Check whether a particular option is checked
- Download Sample Code
- See Also
- Categories
- Php работа с checkbox
- Обработка флажков
- Форма ввода данных
- Переключатели
- Форма ввода данных
- Список
- Форма ввода данных
- Форма ввода данных
- Обработка чекбоксов в PHP
- Одиночный чекбокс
- Группа че-боксов
- Проверка, выбран ли конкретный вариант
- Скачать пример кода
- Read if Checkbox Is Checked in PHP
- Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
Handling checkbox in a PHP form processor
This tutorial will introduce HTML check boxes and how to deal with them in PHP.
Single check box
Let’s create a simple form with a single check box.
form action="checkbox-form.php" method="post"> Do you need wheelchair access? input type="checkbox" name="formWheelchair" value="Yes" /> input type="submit" name="formSubmit" value="Submit" /> form>
In the PHP script (checkbox-form.php), we can get the submitted option from the $_POST array. If $_POST[‘formWheelchair’] is “Yes”, then the box was checked. If the check box was not checked, $_POST[‘formWheelchair’] won’t be set.
Here’s an example of PHP handling the form:
php if(isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') echo "Need wheelchair access."; > else echo "Do not Need wheelchair access."; > ?>
The value of $_POST[‘formSubmit’] is set to ‘Yes’ since the value attribute in the input tag is ‘Yes’.
input type="checkbox" name="formWheelchair" value="Yes" />
You can set the value to be a ‘1’ or ‘on’ instead of ‘Yes’. Make sure the check in the PHP code is also updated accordingly.
Check box group
There are often situations where a group of related checkboxes are needed on a form. The advantage of check box group is that the user can select more than one options. (unlike a radio group where only one option could be selected from a group).
Let’s build on the above example and give the user a list of buildings that he is requesting door access to.
form action="checkbox-form.php" method="post"> Which buildings do you want access to?br /> input type="checkbox" name="formDoor[]" value="A" />Acorn Buildingbr /> input type="checkbox" name="formDoor[]" value="B" />Brown Hallbr /> input type="checkbox" name="formDoor[]" value="C" />Carnegie Complexbr /> input type="checkbox" name="formDoor[]" value="D" />Drake Commonsbr /> input type="checkbox" name="formDoor[]" value="E" />Elliot House input type="submit" name="formSubmit" value="Submit" /> form>
Please note that the checkboxes have the exact same name ( formDoor[ ] ). Also notice that each name ends in [ ] . Using the same name indicates that these checkboxes are all related. Using [ ] indicates that the selected values will be accessed by PHP script as an array. That is, $_POST[‘formDoor’] won’t return a single string as in the example above; it will instead return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST[‘formDoor’] would be an array consisting of: . Here’s an example of how to retrieve the array of values and display them:
php $aDoor = $_POST['formDoor']; if(empty($aDoor)) echo("You didn't select any buildings."); > else $N = count($aDoor); echo("You selected $N door(s): "); for($i=0; $i $N; $i++) echo($aDoor[$i] . " "); > > ?>
If no checkboxes are checked, $_POST[‘formDoor’] will not be set, so use the “empty” function to check for this case. If it’s not empty, then this example just loops through the array ( using the “count” function to determine the size of the array ) and prints out the building codes for the buildings that were checked.
If the check box against ‘Acorn Building’ is checked, then the array will contain value ‘A’. similarly, if ‘Carnegie Complex’ is selected, the array will contain C.
Check whether a particular option is checked
It is often required to check whether a particular option is checked out of all the available items in the checkbox group. Here is the function to do the check:
function IsChecked($chkname,$value) if(!empty($_POST[$chkname])) foreach($_POST[$chkname] as $chkval) if($chkval == $value) return true; > > > return false; >
In order to use it, just call IsChecked(chkboxname,value). For example,
if(IsChecked('formDoor','A')) //do somthing . > //or use in a calculation . $price += IsChecked('formDoor','A') ? 10 : 0; $price += IsChecked('formDoor','B') ? 20 : 0;
Download Sample Code
Download the PHP form checkbox sample code: php-form-checkbox.zip.
See Also
Categories
- Calculation Forms
- HTML Forms
- PHP Form Handling
- Form Action
- Contact Forms
- Code Snippets
- Best Practices
- HTML5 Forms
- Form Widgets
- jQuery Form Handling
- Email Forms
- Form Mail
- Web Forms
- Checkboxes
- File Upload
- Google Forms
Php работа с checkbox
Формы могут содержать различные элементы — текстовые поля, флажки, переключатели и т.д., обработка которых имеет свои особенности.
Обработка флажков
Флажки или чекбоксы (html-элемент ) могут находиться в двух состояниях: отмеченном (checked) и неотмеченном. Например:
Если флажок находится в неотмеченном состоянии, например:
то при отправке формы значение данного флажка не передается на сервер.
Если флажок отмечен, то при отправке на сервер для поля remember будет передано значение on :
Если нас не устраивает значение on , то с помощью атрибута value мы можем установить нужное нам значение:
Иногда необходимо создать набор чекбоксов, где можно выбрать несколько значений. Например:
"; > ?>Форма ввода данных
ASP.NET:
PHP:
Node.js:
В этом случае значение атрибута name должно иметь квадратные скобки. И тогда после отправки сервер будет получать массив отмеченных значений:
$technologies = $_POST["technologies"]; foreach($technologies as $item) echo "$item
";
В данном случае переменная $technologies будет представлять массив, который можно перебрать и выполнять все другие операции с массивами.
Переключатели
Переключатели или радиокнопки позволяют сделать выбор между несколькими взаимоисключающими вариантами:
?>Форма ввода данных
ASP.NET
PHP
Node.js
На сервер передается значение атрибута value у выбранного переключателя. Получение переданного значения:
Список
Список представляет элемент select , который предоставляет выбор одного или нескольких элементов:
?>Форма ввода данных
Элемент содержит ряд вариантов выбора в виде элементов :
Получить выбранный элемент в коде PHP как и обычное одиночное значение:
Но элемент также позволяет сделать множественный выбор. И в этом случае обработка выбранных значений изменяется, так как сервер получает массив значений:
"; > ?>Форма ввода данных
Такие списки имеют атрибут multiple=»multiple» . Для передачи массива также указываются в атрибуте name квадратные скобки: name=»courses[]»
Обработка чекбоксов в PHP
В этой статье мы расскажем о input type checkbox HTML , и том, как они обрабатываются в PHP .
Одиночный чекбокс
Создадим простую форму с одним чекбоксом:
В PHP скрипте ( checkbox-form.php ) мы можем получить выбранный вариант из массива $_POST . Если $_POST[‘formWheelchair’] имеет значение » Yes «, то флажок для варианта установлен. Если флажок не был установлен, $_POST[‘formWheelchair’] не будет задан.
Вот пример обработки формы в PHP :
Для $_POST[‘formSubmit’] было установлено значение “ Yes ”, так как это значение задано в атрибуте чекбокса value :
Вместо “ Yes ” вы можете установить значение » 1 » или » on «. Убедитесь, что код проверки в скрипте PHP также обновлен.
Группа че-боксов
Иногда нужно вывести в форме группу связанных PHP input type checkbox . Преимущество группы чекбоксов заключается в том, что пользователь может выбрать несколько вариантов. В отличие от радиокнопки, где из группы может быть выбран только один вариант.
Возьмем приведенный выше пример и на его основе предоставим пользователю список зданий:
Обратите внимание, что input type checkbox имеют одно и то же имя ( formDoor[] ). И что каждое имя оканчивается на [] . Используя одно имя, мы указываем на то, что чекбоксы связаны. С помощью [] мы указываем, что выбранные значения будут доступны для PHP скрипта в виде массива. То есть, $_POST[‘formDoor’] возвращает не одну строку, как в приведенном выше примере; вместо этого возвращается массив, состоящий из всех значений чекбоксов, которые были выбраны.
Например, если я выбрал все варианты, $_POST[‘formDoor’] будет представлять собой массив, состоящий из: . Ниже приводится пример, как вывести значение массива:
Если ни один из вариантов не выбран, $_POST[‘formDoor’] не будет задан, поэтому для проверки этого случая используйте » пустую » функцию. Если значение задано, то мы перебираем массив через цикл с помощью функции count() , которая возвращает размер массива и выводит здания, которые были выбраны.
Если флажок установлен для варианта » Acorn Building «, то массив будет содержать значение ‘ A ‘. Аналогично, если выбран » Carnegie Complex «, массив будет содержать C .
Проверка, выбран ли конкретный вариант
Часто требуется проверить, выбран ли какой-либо конкретный вариант из всех доступных элементов в группе HTML input type checkbox . Вот функция, которая осуществляет такую проверку:
function IsChecked($chkname,$value) < if(!empty($_POST[$chkname])) < foreach($_POST[$chkname] as $chkval) < if($chkval == $value) < return true; >> > return false; >
Чтобы использовать ее, просто вызовите IsChecked ( имя_чекбокса, значение ). Например:
if(IsChecked('formDoor','A')) < //сделать что-то . >//или использовать в расчете . $price += IsChecked('formDoor','A') ? 10 : 0; $price += IsChecked('formDoor','B') ? 20 : 0;
Скачать пример кода
Скачать PHP код примера формы с PHP input type checkbox .
Read if Checkbox Is Checked in PHP
- Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
- Use the in_array() Function to Read if the Checkbox Is Checked for Checkboxes as an Array
- Use the isset() Function With Ternary Function to Read if the Checkbox Is Checked
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.
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.
# html 5 form action="index.php" method="post" > input type="checkbox" name="test1" value="value1"> Option 1 input type="checkbox" name="test2" value="value2"> Option 2 input type="submit" value="Submit"> form>
#php 7.x php if(isset($_POST['test1'])) echo "checked value1"."
"; > if(isset($_POST['test2'])) echo "checked value2"; > ?>
checked value1 checked value2