knight007
knight007

Reputation: 55

How to get non repeated element in array?

   (
      "userServiceIds": "1,2,3",
      "enggServiceIds": "4,5,6,2,1",
   )

As In these array we need Only enggServiceIds only where It must not be repeated in userServiceIds

As my required result is : - 4,5,6 only

the code must be run in PHP

I have tried this code

$input = array("$data[userServiceIds]" , "$data[enggServiceIds]");
            $result = implode(',',$input);
            $str = implode(',',array_unique(explode(',', $result)));

but the result is :- 1,2,3,4,5,6

As my required result is : - 4,5,6 only

Upvotes: 2

Views: 111

Answers (3)

Junaid
Junaid

Reputation: 610

solution:

$array1 = array(1,2,3);
$array2 = array(3,4,5,6);
$resultarray = array();
$resultarray = array_diff($array2, $array1);

result:

Array ( [1] => 4 [2] => 5 [3] => 6 )

Upvotes: 1

Bilal Akbar
Bilal Akbar

Reputation: 4930

As the input is JSON, convert it to array first. Then using array_diff

$json = '{
  "userServiceIds": "1,2,3",
  "enggServiceIds": "4,5,6,2,1"
}';

$aData = json_decode($json, true);

$aResult = array_diff(explode(',',$aData['enggServiceIds']), explode(',',$aData['userServiceIds']));

print_r($aResult);

Upvotes: 2

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6647

read up on array_diff

$userServiceIds = [1,2,3];
$enggServiceIds = [4,5,6,2,1];

var_dump(array_diff($enggServiceIds, $userServiceIds));

returns:

array(3) {
  [0]=>
  int(4)
  [1]=>
  int(5)
  [2]=>
  int(6)
}

live preview

Upvotes: 1

Related Questions