PHP:不区分大小写的“array_diff”

2022-08-30 20:16:18

我有以下两个数组和代码来查找array_diff:

$obs_ws = array("you", "your", "may", "me", "my", "etc");
$all_ws = array("LOVE", "World", "Your", "my", "etc", "CoDe");

$final_ws = array_diff($all_ws, $obs_ws);

上面的代码给出输出数组为:

$final_ws = array("LOVE", "World", "Your", "CoDe");

但我希望它是:

$final_ws = array("LOVE", "World", "CoDe");

注意“您的”未被删除,这可能是由于“Y”在第二个数组中大写。我也想排除“Your”,那么PHP中是否有任何不区分大小写的版本。array_diff

我尝试array_udiff,但我没有确切地了解如何在我的问题中使用它

谢谢


答案 1

尝试将 strcasecmp 作为第三个参数传递给array_udiff函数:

<?php
$obs_ws = array("you", "your", "may", "me", "my", "etc");
$all_ws = array("LOVE", "World", "Your", "my", "etc", "CoDe");

$final_ws = array_udiff($all_ws, $obs_ws, 'strcasecmp');

print_r($final_ws);

输出:

Array
(
    [0] => LOVE
    [1] => World
    [5] => CoDe
)

答案 2

你走在正确的轨道上。这是我的建议:

function array_casecmp($arr1,$arr2){
    return array_udiff($arr1,$arr2,'strcasecmp');
}


$obs_ws = array("you", "your", "may", "me", "my", "etc");
$all_ws = array("LOVE", "World", "Your", "my", "etc", "CoDe");
var_dump( array_casecmp($all_ws,$obs_ws) );