How can I get case-sensitive return from array_int

2019-02-14 18:59发布

问题:

I have two arrays and I need to compare that and return matched value from array1. Please refer my code below,

$array1 = array("a" => "Green", "Red", "Blue");
$array2 = array("b" => "grEEn", "yellow", "red");
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));

print_r($result);

My result is,

Array
(
    [a] => green
    [0] => red
)

But my expected result is I want get it from array1 like:

Array
(
    [a] => Green
    [0] => Red
)

回答1:

This is because you put all values to lowercase. Just change to array_uintersect() and use strcasecmp() as callback function to compare them case-insensitive, like this:

$result = array_uintersect($array1, $array2, "strcasecmp");

output:

Array ( [a] => Green [0] => Red )