Search code examples
phparraysarray-intersect

display text depending on possibilities


I have 6 values. out which user can selects any of those values. Out of that 6 values 3 are withplans and 3 are withoutplans. According to user selected values I have to show links like below:

  1. withplan link1
  2. withplan link2
  3. withplan link3

OR

  1. withoutplan link4
  2. withoutplan link5
  3. withoutplan link6

I have made three arrays : $userSelected , $targetWith , $targetWithout

 $targetWith = array('val1', 'val2', 'val3'); 

    $targetWithout = array('val4', 'val5', 'val6'); 

There are 3 possibilities in user selection.

Possibility 1: User can select one from with and one from without($userSelected = array('val1','val4');), so that time OR will show.

Possibility 2: If user selects only withplans($userSelected = array('val1','val2');) then OR should not be shown.

Possibility 3: if user selects only withoutplans($userSelected = array('val5','val6');) then OR should not be shown.

To display OR I have used array_intersect but that is not working as expected. If user selects only with plans then OR is getting displayed.

  if( (count(array_intersect($userSelected , $targetWith)) != count($targetWith)) || (count(array_intersect($userSelected , $targetWithout)) != count($targetWithout))){
    // all of $target not is in $userSelected 
  
       echo   '<p><strong>-Or-</strong></p>';
}

I have also tried

if((count(array_intersect($userSelected , $targetWith)) > 0) || (count(array_intersect($userSelected , $targetWithout)) > 0)){
     // at least one of $target is in $userSelected 
 
        echo  '<p><strong>-Or-</strong></p>';
}

Using both above codes, OR is getting displayed for 2,3 possibilities. which should be shown.

I am not getting whats going wrong. How should be that code? If there is any other way to achieve that possibilities please suggest. Please help and guide. thanks in advance.


Solution

  • Assuming you want to determine if the user's selection(s) are present in both arrays, you can simply use array_intersect twice to check that.

    <?php
    
    // Ex. http://sandbox.onlinephpfunctions.com/code/248e7414d6a3fdbb2555ac206455a7fa2e894561
    
    $with = ['val1', 'val2', 'val3'];
    $without = ['val4', 'val5', 'val6'];
    
    $userSelections = ['val1', 'val6'];
    
    $inBoth = 
        !empty(array_intersect($userSelections, $with)) && 
        !empty(array_intersect($userSelections, $without));
    
    if ($inBoth) {
        echo '<p><strong>-Or-</strong></p>';
    }