4

Is there any function similar to "array_intersect" but it is in mode case-insensitive and ignoring tildes?

The array_intersect PHP function compares array elements with === so I do not get the expected result.

For example, I want this code :

$array1 = array("a" => "gréen", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

Outputs gréen and red. In default array_intersect function just red is proposed (normal cause ===).

Any solution ?

Thank you in advance

Dayron Gallardo
  • 1,502
  • 2
  • 21
  • 37

2 Answers2

17
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));
hindmost
  • 7,125
  • 3
  • 27
  • 39
  • Sorry, I forgot to specify that it should also ignore the tildes. Anyway your solution is correct for case-insensitive. – Dayron Gallardo Feb 11 '14 at 12:15
  • this only works if the result can be lowercase, not if for example, the first array is all upper and the second is lower but the result need to upper – DarkMukke May 13 '15 at 07:55
  • 1
    @DarkMukke Here is no problem at all. Just replace `'strtolower'` with `'strtoupper'` and you'll get the result in uppercase – hindmost May 13 '15 at 09:49
  • @hindmost so what happens if you code this function as a helper method in a framework where you don't know what if its going to be uppercase, lowercase or mixed ? – DarkMukke May 13 '15 at 09:59
  • this returns the strtolower-ed values instead of the original ones; the accepted answer returns the correct values – Stefan Gabos Jan 24 '18 at 18:08
7
<?php

function to_lower_and_without_tildes($str,$encoding="UTF-8") {
  $str = preg_replace('/&([^;])[^;]*;/',"$1",htmlentities(mb_strtolower($str,$encoding),null,$encoding));
  return $str;
}

function compare_function($a,$b) {
  return strcmp(to_lower_and_without_tildes($a), to_lower_and_without_tildes($b));
}

$array1 = array("a" => "gréen", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_uintersect($array1, $array2,"compare_function");
print_r($result);

output:

Array
(
    [a] => gréen
    [0] => red
)
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
  • 1
    I know it is an old topic, but there is an error in this function, that causes it to miss some matching keys. Actually, running the exact same code as presented in this answer on PHP 7.1.23, I get as result only "red". The reason for that is that the comparison function `compare_function` should return -1, 0 or 1, depending on whether `$a` is <, =, or > than `$b`, respectively. To fix this `return strcmp(to_lower_and_without_tildes($a), to_lower_and_without_tildes($b));` should be used. – Thiago Barcala Mar 11 '19 at 12:50
  • I edited the answer to incorporate @ThiagoBarcala's comment, as the answer in its previous state was not fully correct – Constantin Groß Sep 24 '19 at 12:11