Top Gun
Top Gun

Reputation: 688

Getting Multiple Specific Array Values

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...

Upvotes: 0

Views: 50

Answers (4)

billyonecan
billyonecan

Reputation: 20250

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';
}

Upvotes: 1

SoftGuide
SoftGuide

Reputation: 336

<?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?

Upvotes: 0

Christian P
Christian P

Reputation: 12240

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

Upvotes: 2

Steve
Steve

Reputation: 20469

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

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

Upvotes: 0

Related Questions