I'm using Drupal 7 and have added checkboxes to a node.

$results = query();

foreach ($results as $result) {
  $name = $result['name'];
  $resultarray[$result['id']] = $name; 

$form['friends'] = array(
  '#title' => "results",
  '#type' => 'checkboxes',
  '#options' => $resultarray,

On my node the checkboxes show.

Now I'm struggling to get the values of selected checkboxes.

function friendmodule_form_submit($form, &$form_state) {

  $friends = $form_state['values']['friends'];

  // do what ever with $friends 

But nothing displays. I've tried echo $friends, print_r, display them as a Drupal message, but nothing is showing.

What should I do to get the values of selected checkboxes?


Assuming that your $resultarray variable in the form actually has some data in it, this code will get you a list of the ids that have been selected:

function friendmodule_form_submit($form, &$form_state) {   
  $friend_ids = array_filter($form_state['values']['friends']);

When a checkboxes element is submitted all of the original option keys will be in the $form_state['values']'friends'] array, but only the ones that have been selected will have a positive value; the rest will have a value of zero, so you need to use array_filter() to extract only the IDs for options that have been selected.

Also, at the moment you have a syntax error in your submit function (an extra closing )), maybe that's what is causing the error.

  • Hi, I did what you said but now im getting Notice: Undefined index: values and array_filter() [function.array-filter]: The first argument should be an array – Sam Healey Jun 14 '12 at 20:12
  • That means your $form_state['values'] array is empty which would indicate quite a big problem with the form. Can you post the exact code you're using for the form and the submit function (including the function declaration itself)? – Clive Jun 14 '12 at 20:18
  • Beware that using this code all values from 'friends' that evaluate as false in PHP will not be retrieved. This includes for example the value "0". – xpereta May 28 '15 at 16:32

Drupal 8

If I have checkboxes "Friends" and options are like

[ ] abc
[ ] def
[ ] ghi
[ ] jkl

And I want to know which options user have marked, then use below function.

if ($form_state->getValue('friends') != NULL) {

  foreach ($form_state->getValue('friends') as $key => $value) {

    if ($value != 0) {

      $friends = $friends . ", " . $key;
      $friends = substr_replace($friends, "", 0, 1);

If user has chosen abc and ghi then you will get 1, 3 as result in $friends. If you wanted to know the value then use

$friends = $friends . ", " . $value;

It worked for me. I hope it will help you as well.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.