php array_intersect with strict type

593 views Asked by At

PHP array_intersect does not have any option for strict type checking as they have given in_array

$array1 = array(true,2);

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

var_dump(array_intersect($array1, $array2));

result is :

array(2) {
  [0] =>  bool(true)
  [1]  =>  int(2)
}

where expected result is

array(1) {
  [0]  =>  int(2)
}

Am I missing something ?

May be question is duplicated with PHP array_intersect() - how does it handle different types?

2

There are 2 answers

0
Verox On

PHP isn't a strongly-typed language, as far as it is concerned anything that isn't false, is true, and will evaluate as such in boolean operations. You can get more info about this on the PHP Manual http://php.net/manual/en/language.types.boolean.php

However, PHP does provide the functionality to strictly check types with ===, as you said array_intersect doesn't use this functionality but it is possible to use array_uintersect to define your own callback function which will do the comparison of the values. http://php.net/manual/en/function.array-uintersect.php

0
Alexey Berezuev On

If you wanna strict array_intersect, you can write your own method, like this:

<?php
    public function array_intersect_strict(array $array1, array $array2) {
        return array_filter($array1, function ($value) use ($array2) {
            return in_array($value, $array2, true);
        });
    }