YaLinqo\Enumerable::intersect PHP Method

intersect() public method

Element keys are values identifying elements. They are used as array keys and are subject to the same rules as array keys, for example, integer 100 and string "100" are considered equal.

Syntax: intersect (other)

Produces the set intersection of two sequences using values as element keys.

Syntax: intersect (other, keySelector {(v, k) ==> value})

Produces the set intersection of two sequences using values produced by keySelector as element keys.

public intersect ( array | Iterator | IteratorAggregate | Enumerable $other, callable | null $keySelector = null ) : Enumerable
$other array | Iterator | IteratorAggregate | Enumerable A sequence whose distinct elements that also appear in the first sequence will be returned.
$keySelector callable | null {(v, k) ==> key} A function to extract the element key from each element. Default: value.
return Enumerable A sequence that contains the elements that form the set intersection of two sequences.
    public function intersect($other, $keySelector = null)
    {
        $other = self::from($other);
        $keySelector = Utils::createLambda($keySelector, 'v,k', Functions::$value);
        return new self(function () use($other, $keySelector) {
            $set = [];
            foreach ($other as $k => $v) {
                $key = $keySelector($v, $k);
                $set[$key] = true;
            }
            foreach ($this as $k => $v) {
                $key = $keySelector($v, $k);
                if (!isset($set[$key])) {
                    continue;
                }
                unset($set[$key]);
                (yield $k => $v);
            }
        });
    }