1

I want to know how to compare 2 arrays in PHP for matches. I've used array_intersect($arr1, $arr2). I want the matches to be case insensitive.

Example:

$arr1 = ['hello', 'how', 'are', 'you'];
$arr2 = ['Hello', 'fine', 'You'];

Expected Output

['hello','you']

Thanks!

Jaxian
  • 1,146
  • 7
  • 14
Asad ullah
  • 620
  • 2
  • 9
  • 26

2 Answers2

3

If the result can be in all lowercase, you can do it like this:

$result = array_intersect(array_map('strtolower', $arr1), array_map('strtolower', $arr2));

Otherwise, you can use array_uintersect which takes a callback for the string comparison. You can then use strcasecmp for case insensitive string comparison.

$result = array_uintersect($arr1, $arr2, "strcasecmp");
aufziehvogel
  • 7,167
  • 5
  • 34
  • 56
1

You can accomplish this quite simply by passing both arrays through array_map() in order to strtolower() (or strtoupper()) them first:

$arr1 = ['hello', 'how', 'are', 'you'];
$arr2 = ['Hello', 'fine', 'You'];

var_dump(
    array_intersect(
        array_map('strtolower', $arr1),
        array_map('strtolower', $arr2)
    )
);

// [ "hello", "you" ]
rickdenhaan
  • 10,857
  • 28
  • 37