PHP: Case-insensitive “array_diff”

纵然是瞬间 提交于 2019-12-12 07:44:00

问题


I have following two arrays and the code to find 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);

Above code giving output array as:

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

But I want it as:

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

Note "Your" is not removed, it may be due to "Y" is in caps in second array. I want to exclude "Your" also, so is there any case-insensitive version of array_diff in PHP.

I tried array_udiff but I am not getting exactly how to use this in my problem

Thanks


回答1:


Try to pass strcasecmp as third parameter to array_udiff function:

<?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);

Output:

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



回答2:


You were on the right track. This is my suggestion:

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) );


来源:https://stackoverflow.com/questions/1875862/php-case-insensitive-array-diff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!