0

I have set a from filed with checkboxes.

<input type="checkbox" name="rights[]" value="1" class="a"> A
<input type="checkbox" name="rights[]" value="2" class="b"> B
<input type="checkbox" name="rights[]" value="3" class="c"> C

Now i want if the user selects option A then i want to set the variable and assign it the value 1. If the user selects multiple values i-e A and B i want to set a variable with the value 'BOTH'.

$right = $this->input->post('rights');

        if (in_array ('1', $right)){

            $rights = '1';
        }

        if (in_array ('2', $right)){
            $rights = '2';  
        }

        if (in_array ('3', $right) ){
            $rights = '3';
        }

        if (array_intersect($right, array('2', '3') ) ){
            $rights = 'both';
        }

i have tried this by using in_array() and array_intersect() function but when the user selects either B or C the variable value set to Both, instead of setting the value to B or C. Any Help...

4 Answers 4

2

Maybe you can use this:

$numOfRights = count($right);

if ($numOfRights > 1) $rights = 'both';
else if ($numOfRights == 1) $rights[0];
else $rights = 'I have no rights'; // probably handle it better
Sign up to request clarification or add additional context in comments.

2 Comments

nice I forgot to handle the 0 count!
@Pete the devil is in the details :)
1

From the documentation for array_intersect():

array_intersect() returns an array containing all the values of array1 that are present in all the arguments.

So if either 2 or 3 is checked, it'll return an array containing that value, so your condition evaluates true which is why $rights = 'both';

You can simplify your code to:

if (!empty($right)) {
  $rights = (count($right) == 1) ? array_shift($right) : 'both';
}

Comments

0

How about just counting the number of elements in the array:

if (count($right) > 1){
    $rights = 'both';
}

Comments

0
<?php
   if (in_array(2, $right) && in_array(3, $right) ){
      $rights = 'both';
   } else if (in_array ('3', $right)){
      $rights = '3';
   } else if (in_array ('2', $right)){
      $rights = '2';  
   } else if (in_array ('1', $right) ){
      $rights = '1';
   }
?>

Something like this?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.