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

2 Answers 2

17
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, I forgot to specify that it should also ignore the tildes. Anyway your solution is correct for case-insensitive.
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 Here is no problem at all. Just replace 'strtolower' with 'strtoupper' and you'll get the result in uppercase
@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 ?
this returns the strtolower-ed values instead of the original ones; the accepted answer returns the correct values
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
)

2 Comments

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.
I edited the answer to incorporate @ThiagoBarcala's comment, as the answer in its previous state was not fully correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.