Sam
Sam

Reputation: 41

How to post blank array (neither NULL nor "") values in php in no checkbox is checked

I have a list of checkboxes and if checked their values are posted to json file which is working fine. When user uncheck all of them I get NULL value in array and if I set its value="" its returns depends :[""]. what I want is if user did not check any checkbox it returns depends:[] only neither NULL nor "".

Here is my code:

<label for="depends">Linked With</label></br>

<input type="checkbox" name="depends[]" value="1"  id="ch2" > 1
<input type="checkbox" name="depends[]" value="2"  id="ch3" > 2
<input type="checkbox" name="depends[]" value="3"  id="ch5" > 3
<input type="checkbox" name="depends[]" value="4"  id="ch6" > 4
<input type="checkbox" name="depends[]" value="5"  id="ch7" > 5
<input type="checkbox" name="depends[]" value="6"  id="ch8" > 6
<input type="checkbox" name="depends[]" value="7"  id="ch9" > 7

in php code I am calling it as

'depends'=>$_POST['depends']

Upvotes: 0

Views: 342

Answers (1)

romph
romph

Reputation: 487

in your php code you can handle it like that :

<?php
    /* if $_POST['depends'] is not empty then you store the value, else you create an empty array [] */
    $var = isset($_POST['depends']) ? $_POST['depends'] : array(); /* you can replace $var */
    print_r($var);
?>

Upvotes: 1

Related Questions