Home > front end >  get array_intersect count without duplicates php
get array_intersect count without duplicates php

Time:10-18

I have 2 arrays:

$first = array(1,1,2,3,4);
$second = array(1,2,3,4,5);

when i use $count = array_intersect($first, $second);, and count($count); the matches, it shows 5, resulting in 1 intersecting twice. I need to get 4, which doesn't count duplicates.

how can I achieve that in php?

thanks in advance.

CodePudding user response:

It's very simple: first make sure your arrays are unique, and then apply array_intersect:

$count = count(array_intersect(array_unique($first), array_unique($second)));

Repro case on 3v4l.

CodePudding user response:

Also, I would like to add these cone I've figured out before finding a better answer.

$result = array_intersect($first, $second);
  $diff = array_diff($result, $second);
   if(!empty($diff)) {
    $result = array_unique($result);
   }
  • Related